0% found this document useful (0 votes)
11 views

Java Script - Detailed Syllabus

this is my java class notes

Uploaded by

kumarsharma05990
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Java Script - Detailed Syllabus

this is my java class notes

Uploaded by

kumarsharma05990
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 114

Contents

Day-1........................................................................................................................................................8
What is JavaScript..............................................................................................................................8
Features of JavaScript......................................................................................................................8
History of JavaScript.........................................................................................................................9
Application of JavaScript.................................................................................................................9
JavaScript Example......................................................................................................................10
3 Places to put JavaScript code....................................................................................................10
1) JavaScript Example : code between the body tag...............................................................10
2) JavaScript Example : code between the head tag...............................................................11
External JavaScript file...........................................................................................................................11
Advantages of External JavaScript..............................................................................................12
Disadvantages of External JavaScript........................................................................................13
Day-2......................................................................................................................................................13
Editors and Their Features...................................................................................................................13
1. Atom..........................................................................................................................................13
2. Notepad++..............................................................................................................................14
3. Sublime Text...........................................................................................................................14
4. Adobe Dreamweaver CC....................................................................................................14
5. Visual Studio Code..............................................................................................................15
Day-3......................................................................................................................................................16
JavaScript output.......................................................................................................................................16
JavaScript Display Possibilities..........................................................................................16
Using innerHTML.........................................................................................................................16
Example........................................................................................................................................16
Using document.write()..........................................................................................................17
Example........................................................................................................................................17
Using window.alert()................................................................................................................17
Example........................................................................................................................................17
Using console.log()....................................................................................................................18
Example........................................................................................................................................18
JavaScript Print............................................................................................................................18
Example........................................................................................................................................18
JavaScript Operators..............................................................................................................................19
JavaScript Arithmetic Operators..................................................................................................19
JavaScript Comparison Operators...............................................................................................20
JavaScript Bitwise Operators........................................................................................................21
JavaScript Logical Operators........................................................................................................21
JavaScript Assignment Operators...............................................................................................22
JavaScript Special Operators........................................................................................................22
Practical on JavaScript operators...............................................................................................................24
JavaScript Assignment.............................................................................................................24
Assignment Examples..........................................................................................................24
JavaScript Addition....................................................................................................................25
Adding...........................................................................................................................................25
JavaScript Multiplication........................................................................................................25
Multiplying..................................................................................................................................26
JavaScript String Comparison..............................................................................................26
Example........................................................................................................................................27
JavaScript Type Operators.....................................................................................................28
JavaScript Bitwise Operators...............................................................................................28
JavaScript Data Types........................................................................................................................30
JavaScript has 8 Datatypes...............................................................................................30
The Object Datatype.............................................................................................................30
The Concept of Data Types...................................................................................................31
Note....................................................................................................................................................31
JavaScript:...................................................................................................................................32
JavaScript Types are Dynamic.............................................................................................32
Example........................................................................................................................................32
JavaScript Strings.......................................................................................................................32
Example........................................................................................................................................32
JavaScript If-else....................................................................................................................................34
JavaScript If statement................................................................................................................34
JavaScript If...else Statement....................................................................................................35
Flowchart of JavaScript If...else statement............................................................................36
avaScript If...else if statement...................................................................................................37
JavaScript Switch...................................................................................................................................38
JavaScript while loop......................................................................................................................39
JavaScript For loop..........................................................................................................................40
Functions...................................................................................................................................................42
Defining functions..................................................................................................................................42
Function declarations........................................................................................................................42
Function expressions.........................................................................................................................43
Calling functions....................................................................................................................................45
Function hoisting...............................................................................................................................46
Day-12...............................................................................................................................................47
Function scope......................................................................................................................................47
Scope and the function stack.................................................................................................................47
Recursion...........................................................................................................................................47
Nested functions and closures...........................................................................................................49
Preservation of variables...................................................................................................................50
Multiply-nested functions..................................................................................................................50
Name conflicts...................................................................................................................................51
Closures.................................................................................................................................................52
Using the arguments object...................................................................................................................54
Function parameters.............................................................................................................................55
Default parameters............................................................................................................................55
Rest parameters.................................................................................................................................55
Arrow functions.....................................................................................................................................56
Shorter functions...............................................................................................................................56
No separate this.................................................................................................................................56
JavaScript Arrays........................................................................................................................................58
Introduction......................................................................................................................................58
Creating an Array................................................................................................................................60
Day-15...............................................................................................................................................62
Indexing Arrays...................................................................................................................................62
Accessing Items in an Array..............................................................................................................63
Adding an Item to an Array................................................................................................................64
Removing an Item from an Array......................................................................................................66
Modifying Items in Arrays...................................................................................................................68
Looping Through an Array.................................................................................................................69
JavaScript Sorting Arrays..................................................................................................................71
Sorting an Array..........................................................................................................................71
Example........................................................................................................................................71
Reversing an Array....................................................................................................................71
Example........................................................................................................................................71
Numeric Sort.................................................................................................................................71
Example........................................................................................................................................72
Example........................................................................................................................................72
The Compare Function.............................................................................................................72
Sorting an Array in Random Order...................................................................................74
Example........................................................................................................................................74
The Fisher Yates Method........................................................................................................74
Example........................................................................................................................................75
Find the Lowest (or Highest) Array Value....................................................................75
Example........................................................................................................................................75
Example........................................................................................................................................75
Using Math.max() on an Array............................................................................................76
Example........................................................................................................................................76
Using Math.min() on an Array.............................................................................................76
Example........................................................................................................................................76
My Min / Max JavaScript Methods.....................................................................................76
Example (Find Max)...............................................................................................................76
Example (Find Min)................................................................................................................77
Sorting Object Arrays...............................................................................................................77
Example........................................................................................................................................77
Example........................................................................................................................................78
Example........................................................................................................................................78
Stable Array sort().....................................................................................................................78
What Is an Object?.................................................................................................................................80
JavaScript String.....................................................................................................................................85
1) By string literal.............................................................................................................................85
JavaScript String Methods................................................................................................................86
Note....................................................................................................................................................86
JavaScript String Length........................................................................................................86
Example........................................................................................................................................86
Extracting String Parts............................................................................................................86
JavaScript String slice()..........................................................................................................87
Example........................................................................................................................................87
Note....................................................................................................................................................87
Examples......................................................................................................................................87
JavaScript String substring()...............................................................................................87
Example........................................................................................................................................87
JavaScript String substr()......................................................................................................88
Example........................................................................................................................................88
Example........................................................................................................................................88
Example........................................................................................................................................88
Replacing String Content.......................................................................................................88
Example........................................................................................................................................88
JavaScript String ReplaceAll().............................................................................................89
Example........................................................................................................................................89
Example........................................................................................................................................89
Note....................................................................................................................................................89
Converting to Upper and Lower Case.............................................................................89
JavaScript String toUpperCase()........................................................................................90
Example........................................................................................................................................90
JavaScript String toLowerCase()........................................................................................90
Example........................................................................................................................................90
JavaScript String concat().....................................................................................................90
Example........................................................................................................................................90
Example........................................................................................................................................90
Note....................................................................................................................................................90
JavaScript String trim()...........................................................................................................91
Example........................................................................................................................................91
JavaScript String trimStart()................................................................................................91
Example........................................................................................................................................91
JavaScript Get Date Methods..........................................................................................................92
The new Date() Constructor.................................................................................................92
Get the Current Time............................................................................................................92
Date Get Methods.......................................................................................................................92
Note 1................................................................................................................................................93
Note 2................................................................................................................................................93
The getFullYear() Method......................................................................................................94
Examples......................................................................................................................................94
JavaScript Events................................................................................................................................95
HTML Events..................................................................................................................................95
Example........................................................................................................................................96
Example........................................................................................................................................96
Example........................................................................................................................................96
Common HTML Events.............................................................................................................96
JavaScript Event Handlers.....................................................................................................97
AngularJS Introduction.......................................................................................................................98
AngularJS is a JavaScript Framework..............................................................................98
AngularJS Extends HTML........................................................................................................98
AngularJS Example.................................................................................................................99
AngularJS Directives...............................................................................................................100
AngularJS Example...............................................................................................................100
AngularJS Example...............................................................................................................100
AngularJS Expressions...........................................................................................................100
AngularJS Example...............................................................................................................100
AngularJS Example...............................................................................................................101
AngularJS ng-model Directive.......................................................................................................102
The ng-model Directive.........................................................................................................102
Example......................................................................................................................................102
Two-Way Binding.......................................................................................................................102
Example......................................................................................................................................103
Validate User Input..................................................................................................................103
Example......................................................................................................................................103
Application Status....................................................................................................................103
Example......................................................................................................................................103
CSS Classes..................................................................................................................................104
Example......................................................................................................................................104
Data Model...................................................................................................................................105
Example......................................................................................................................................105
HTML View....................................................................................................................................105
Example......................................................................................................................................105
Example......................................................................................................................................105
The ng-model Directive...........................................................................................................106
Example......................................................................................................................................106
Two-way Binding.......................................................................................................................106
Example......................................................................................................................................106
AngularJS Controller...............................................................................................................107
Example......................................................................................................................................107
AngularJS Filters.................................................................................................................................108
AngularJS Filters.......................................................................................................................108
Adding Filters to Expressions............................................................................................108
Example......................................................................................................................................108
Example......................................................................................................................................109
Adding Filters to Directives................................................................................................109
Example......................................................................................................................................109
The currency Filter..................................................................................................................109
Example......................................................................................................................................110
The filter Filter...........................................................................................................................110
Example......................................................................................................................................110
Filter an Array Based on User Input..............................................................................110
Example......................................................................................................................................111
Sort an Array Based on User Input.................................................................................111
Example......................................................................................................................................112
Custom Filters............................................................................................................................113
Example......................................................................................................................................113
Day-1
What is JavaScript
JavaScript (js) is a light-weight object-oriented programming language which
is used by several websites for scripting the webpages. It is an interpreted,
full-fledged programming language that enables dynamic interactivity on
websites when applied to an HTML document. It was introduced in the year
1995 for adding programs to the webpages in the Netscape Navigator
browser. Since then, it has been adopted by all other graphical web
browsers. With JavaScript, users can build modern web applications to
interact directly without reloading the page every time. The traditional
website uses js to provide several forms of interactivity and simplicity.

Although, JavaScript has no connectivity with Java programming language.


The name was suggested and provided in the times when Java was gaining
popularity in the market. In addition to web browsers, databases such as
CouchDB and MongoDB uses JavaScript as their scripting and query
language.

Features of JavaScript
There are following features of JavaScript:

1. All popular web browsers support JavaScript as they provide built-in execution
environments.
2. JavaScript follows the syntax and structure of the C programming language.
Thus, it is a structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).
4. JavaScript is an object-oriented programming language that uses prototypes
rather than using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows,
macOS, etc.
8. It provides good control to the users over the web browsers.

History of JavaScript
In 1993, Mosaic, the first popular web browser, came into existence. In
the year 1994, Netscape was founded by Marc Andreessen. He realized
that the web needed to become more dynamic. Thus, a 'glue language' was
believed to be provided to HTML to make web designing easy for designers
and part-time programmers. Consequently, in 1995, the company
recruited Brendan Eich intending to implement and embed Scheme
programming language to the browser. But, before Brendan could start, the
company merged with Sun Microsystems for adding Java into its Navigator
so that it could compete with Microsoft over the web technologies and
platforms. Now, two languages were there: Java and the scripting language.
Further, Netscape decided to give a similar name to the scripting language
as Java's. It led to 'Javascript'. Finally, in May 1995, Marc Andreessen coined
the first code of Javascript named 'Mocha'. Later, the marketing team
replaced the name with 'LiveScript'. But, due to trademark reasons and
certain other reasons, in December 1995, the language was finally renamed
to 'JavaScript'. From then, JavaScript came into existence.

Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:

o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm
dialog box and prompt dialog box),
o Displaying clocks etc.

JavaScript Example
<script>
document.write("Hello JavaScript by JavaScript");
</script>

1. <script type="text/javascript">
2. document.write("JavaScript is a simple language for javatpoint learners");
3. </script>

The script tag specifies that we are using JavaScript.

The text/javascript is the content type that provides information to the


browser about the data.

The document.write() function is used to display dynamic content through


JavaScript. We will learn about document object in detail later.

3 Places to put JavaScript code


1. Between the body tag of html
2. Between the head tag of html
3. In .js file (external javaScript)

1) JavaScript Example : code between the body tag


In the above example, we have displayed the dynamic content using
JavaScript. Let’s see the simple example of JavaScript that displays alert
dialog box.

1. <script type="text/javascript">
2. alert("Hello Javatpoint");
3. </script>
2) JavaScript Example : code between the head tag
Let’s see the same example of displaying alert dialog box of JavaScript that
is contained inside the head tag.

In this example, we are creating a function msg(). To create function in


JavaScript, you need to write function with function_name as given below.

To call function, you need to work on event. Here we are using onclick event
to call msg() function.

1. <html>
2. <head>
3. <script type="text/javascript">
4. function msg(){
5. alert("Hello Javatpoint");
6. }
7. </script>
8. </head>
9. <body>
10.<p>Welcome to JavaScript</p>
11. <form>
12.<input type="button" value="click" onclick="msg()"/>
13. </form>
14.</body>
15. </html>

External JavaScript file


We can create external JavaScript file and embed it in many html page.

It provides code re usability because single JavaScript file can be used in


several html pages.

An external JavaScript file must be saved by .js extension. It is recommended


to embed all JavaScript files into a single file. It increases the speed of the
webpage.

Let's create an external JavaScript file that prints Hello Javatpoint in a alert
dialog box.

message.js

1. function msg(){
2. alert("Hello Javatpoint");
3. }

Let's include the JavaScript file into html page. It calls the JavaScript
function on button click.

index.html
1. <html>
2. <head>
3. <script type="text/javascript" src="message.js"></script>
4. </head>
5. <body>
6. <p>Welcome to JavaScript</p>
7. <form>
8. <input type="button" value="click" onclick="msg()"/>
9. </form>
10.</body>
11. </html>
Advantages of External JavaScript
There will be following benefits if a user creates an external javascript:

1. It helps in the reusability of code in more than one HTML file.


2. It allows easy code readability.
3. It is time-efficient as web browsers cache the external js files, which further
reduces the page loading time.
4. It enables both web designers and coders to work with html and js files
parallelly and separately, i.e., without facing any code conflictions.
5. The length of the code reduces as only we need to specify the location of the
js file.

Disadvantages of External JavaScript


There are the following disadvantages of external files:

1. The stealer may download the coder's code using the url of the js file.
2. If two js files are dependent on one another, then a failure in one file may
affect the execution of the other dependent file.
3. The web browser needs to make an additional http request to get the js code.
4. A tiny to a large change in the js code may cause unexpected results in all its
dependent files.
5. We need to check each file that depends on the commonly created external
javascript file.
6. If it is a few lines of code, then better to implement the internal javascript
code.

Day-2

Editors and Their Features

1. Atom
Atom is an open source and free code editor. It was released by
GitHub in 2014.

Key Features of Atom


 It has 81 built-in packages and 8,700 additional packages that
can be installed.
 Since it’s an open-source text-editor, its code is available on

GitHub and can be used by the developers to extend and edit its
source code.
 Atom supports multiple sections within a single interface thus
helping the developers to write code side by side.
 It also provides flexible auto-completion and syntax correction
along with cross-platform editing.
2. Notepad++
Notepad++ is a free,open-source, multi-language code editor which
was initially developed for Windows-based computers. It uses
‘Scintilla’ as the editing component and is written in C++.

Key Features of Notepad++


 It is a lightweight software i.e. smaller program size. It is also
available as an application on mobiles and its source code is
available on GitHub.
 Since it is an open-source code editor, it is extendable and the
users can add functionalities as per their needs or add plugins
from different communities.
 It is customizable thus allowing the users to personalize the
features as per their preferences.
3. Sublime Text
It is a cross-platform editor with Python API. Its latest version was
released on 29 January 2013.

Key Features
 It has the provision of simultaneous editing i.e. it is possible to
apply changes to several domains at a particular time.
 It provides many actions such as- command palette, file

switching,goto symbols,multi-edit,alignment,bracket-
highlighter,etc.
 Sublime falls under the category of freemium software i.e. we
need to pay additional money to enjoy all its features.
 Some of the packages of sublime are open-source and are
available on git.
4. Adobe Dreamweaver CC
Adobe Dreamweaver CC has been developed by Adobe Inc.
However, it is a closed-source software and works well only within
an Adobe ecosystem.

Key Features
 It has proven to be an important tool in the domain of web-

designing using the aesthetic cloud libraries of Adobe promoting


colors,graphics,layers,etc.
 It can be used as a text as well as WYSIWYG(what you see is
what you get) editor i.e. code can be edited with or without a
visual guide.
 This gives the developers additional features of previewing the
end results of the code.
 It is useful for full-stack development.
5. Visual Studio Code
Visual Studio Code was developed by Microsoft as a multi-platform
and multi-language software.

Key Features
 It has the features of built-in Git commands, debugging of code

right from the editor, live preview of the web from server, smart
code-completion using IntelliSense and many more.
 It’s a free and open-source software that is one of the most
popular developers’ tool.
 The most prominent feature of Visual Studio Code is its
interactive debugger which enables execution of debugging
commands on the console.
 IntelliSense of VS Code has proven to be extremely beneficial
for code understanding, navigation and refactoring.
Day-3

JavaScript output
JavaScript Display Possibilities

JavaScript can "display" data in different ways:

 Writing into an HTML element, using innerHTML.


 Writing into the HTML output using document.write().
 Writing into an alert box, using window.alert().
 Writing into the browser console, using console.log().

Using innerHTML
To access an HTML element, JavaScript can use
the document.getElementById(id) method.

The id attribute defines the HTML element. The innerHTML property defines the
HTML content:

Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My First Paragraph</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>

</body>
</html>
Using document.write()
For testing purposes, it is convenient to use document.write():

Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
document.write(5 + 6);
</script>

</body>
</html>

Using window.alert()
You can use an alert box to display data:

Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>


<p>My first paragraph.</p>

<script>
window.alert(5 + 6);
</script>

</body>
</html>
Using console.log()
For debugging purposes, you can call the console.log() method in the browser
to display data.

Example
<!DOCTYPE html>
<html>
<body>

<script>
console.log(5 + 6);
</script>

</body>
</html>

JavaScript Print
JavaScript does not have any print object or print methods.

You cannot access output devices from JavaScript.

The only exception is that you can call the window.print() method in the browser
to print the content of the current window.

Example
<!DOCTYPE html>
<html>
<body>

<button onclick="window.print()">Print this page</button>

</body>
</html>
Day-4

JavaScript Operators
JavaScript operators are symbols that are used to perform operations on
operands. For example:

1. var sum=10+20;

Here, + is the arithmetic operator and = is the assignment operator.

There are following types of operators in JavaScript.

1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators

JavaScript Arithmetic Operators


Arithmetic operators are used to perform arithmetic operations on the
operands. The following operators are known as JavaScript arithmetic
operators.

Operator Description Example

+ Addition 10+20 = 30

- Subtraction 20-10 = 10
* Multiplication 10*20 = 200

/ Division 20/10 = 2

% Modulus (Remainder) 20%10 = 0

++ Increment var a=10; a++; Now a = 11

-- Decrement var a=10; a--; Now a = 9

JavaScript Comparison Operators


The JavaScript comparison operator compares the two operands. The
comparison operators are as follows:

Operator Description Example

== Is equal to 10==20 = false

=== Identical (equal and of same type) 10==20 = false

!= Not equal to 10!=20 = true

!== Not Identical 20!==20 = false

> Greater than 20>10 = true

>= Greater than or equal to 20>=10 = true

< Less than 20<10 = false

<= Less than or equal to 20<=10 = false


JavaScript Bitwise Operators
The bitwise operators perform bitwise operations on operands. The bitwise
operators are as follows:

Operator Description Example

& Bitwise AND (10==20 & 20==33) = false

| Bitwise OR (10==20 | 20==33) = false

^ Bitwise XOR (10==20 ^ 20==33) = false

~ Bitwise NOT (~10) = -10

<< Bitwise Left Shift (10<<2) = 40

>> Bitwise Right Shift (10>>2) = 2

>>> Bitwise Right Shift with Zero (10>>>2) = 2

JavaScript Logical Operators


The following operators are known as JavaScript logical operators.

Operator Description Example

&& Logical AND (10==20 && 20==33) = false

|| Logical OR (10==20 || 20==33) = false

! Logical Not !(10==20) = true


JavaScript Assignment Operators
The following operators are known as JavaScript assignment operators.

Operator Description Example

= Assign 10+10 = 20

+= Add and assign var a=10; a+=20; Now a = 30

-= Subtract and assign var a=20; a-=10; Now a = 10

*= Multiply and assign var a=10; a*=20; Now a = 200

/= Divide and assign var a=10; a/=2; Now a = 5

%= Modulus and assign var a=10; a%=2; Now a = 0

JavaScript Special Operators


The following operators are known as JavaScript special operators.

Operator Description

(?:) Conditional Operator returns value based on the condition. It is like if-
else.

, Comma Operator allows multiple expressions to be evaluated as


single statement.

delete Delete Operator deletes a property from the object.

in In Operator checks if object has the given property


instanceo checks if the object is an instance of given type
f

new creates an instance (object)

typeof checks the type of object.

void it discards the expression's return value.

yield checks what is returned in a generator by the generator's iterator.


Day-5
Practical on JavaScript operators.
JavaScript Assignment
The Assignment Operator (=) assigns a value to a variable:

Assignment Examples
let x = 10;

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Operators</h1>
<h2>The Assignment (=) Operator</h2>

<p id="demo"></p>

<script>
// Assign the value 5 to x
let x = 5;
// Assign the value 2 to y
let y = 2;
// Assign the value x + y to z
let z = x + y;
// Display z
document.getElementById("demo").innerHTML = "The sum of x + y is: " + z;
</script>

</body>
</html>
JavaScript Addition
The Addition Operator (+) adds numbers:

Adding
let x = 5;
let y = 2;
let z = x + y;

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Arithmetic</h1>
<h2>The * Operator</h2>

<p id="demo"></p>

<script>
let x = 5;
let y = 2;
let z = x * y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

JavaScript Multiplication
The Multiplication Operator (*) multiplies numbers:
Multiplying
let x = 5;
let y = 2;
let z = x * y;

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Arithmetic</h1>
<h2>The * Operator</h2>

<p id="demo"></p>

<script>
let x = 5;
let y = 2;
let z = x * y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>

JavaScript String Comparison


All the comparison operators above can also be used on strings:

Example
let text1 = "A";
let text2 = "B";
let result = text1 < text2;
<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Operators</h1>

<p>All conditional operators can be used on both numbers and


strings.</p>

<p id="demo"></p>

<script>
let text1 = "A";
let text2 = "B";
let result = text1 < text2;
document.getElementById("demo").innerHTML = "Is A less than B? " +
result;
</script>

</body>
</html>

JavaScript Type Operators


Operator Description

typeof Returns the type of a variable


instanceof Returns true if an object is an instance of an object
type

JavaScript Bitwise Operators


Bit operators work on 32 bits numbers.

Any numeric operand in the operation is converted into a 32 bit number. The
result is converted back to a JavaScript number.

Operator Description Example Same as Result Decimal

& AND 5&1 0101 & 0001 0001 1

| OR 5|1 0101 | 0001 0101 5

~ NOT ~5 ~0101 1010 10

^ XOR 5^1 0101 ^ 0001 0100 4

<< left shift 5 << 1 0101 << 1 1010 10

>> right shift 5 >> 1 0101 >> 1 0010 2

>>> unsigned right shift 5 >>> 1 0101 >>> 1 0010 2


The examples above uses 4 bits unsigned examples. But JavaScript uses 32-bit
signed numbers.
Because of this, in JavaScript, ~ 5 will not return 10. It will return -6.
~00000000000000000000000000000101 will return
11111111111111111111111111111010
Day-6
JavaScript Data Types
JavaScript has 8 Datatypes
1. String
2. Number
3. Bigint
4. Boolean
5. Undefined
6. Null
7. Symbol
8. Object

The Object Datatype


The object data type can contain:

1. An object
2. An array
3. A date

// Numbers:
let length = 16;
let weight = 7.5;

// Strings:
let color = "Yellow";
let lastName = "Johnson";

// Booleans
let x = true;
let y = false;

// Object:
const person = {firstName:"John", lastName:"Doe"};

// Array object:
const cars = ["Saab", "Volvo", "BMW"];
// Date object:
const date = new Date("2022-03-25");

The Concept of Data Types


In programming, data types is an important concept.

To be able to operate on variables, it is important to know something about the


type.

Without data types, a computer cannot safely solve this:

let x = 16 + "Volvo";

Does it make any sense to add "Volvo" to sixteen? Will it produce an error or will
it produce a result?

JavaScript will treat the example above as:

let x = "16" + "Volvo";

Note
When adding a number and a string, JavaScript will treat the number as a string.

let x = 16 + "Volvo";
let x = "Volvo" + 16;

JavaScript evaluates expressions from left to right. Different sequences can


produce different results:
JavaScript:
let x = 16 + 4 + "Volvo";

JavaScript Types are Dynamic


JavaScript has dynamic types. This means that the same variable can be used to
hold different data types:

Example
let x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String

JavaScript Strings
A string (or a text string) is a series of characters like "John Doe".

Strings are written with quotes. You can use single or double quotes:

Example
// Using double quotes:
let carName1 = "Volvo XC60";

// Using single quotes:


let carName2 = 'Volvo XC60';

You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Strings</h2>

<p>You can use quotes inside a string, as long as they don't match the
quotes surrounding the string:</p>

<p id="demo"></p>

<script>
let answer1 = "It's alright";
let answer2 = "He is called 'Johnny'";
let answer3 = 'He is called "Johnny"';

document.getElementById("demo").innerHTML =
answer1 + "<br>" +
answer2 + "<br>" +
answer3;
</script>

</body>
</html>
Day-7
JavaScript If-else
The JavaScript if-else statement is used to execute the code whether
condition is true or false. There are three forms of if statement in JavaScript.

1. If Statement
2. If else statement
3. if else if statement

JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript
if statement is given below.

if(expression){
//content to be evaluated
}
Flowchart of JavaScript If statement
Let’s see the simple example of if statement in java script.

1. <script>
2. var a=20;
3. if(a>10){
4. document.write("value of a is greater than 10");
5. }
6. </script>

JavaScript If...else Statement


It evaluates the content whether condition is true of false. The syntax of
JavaScript if-else statement is given below.

1. if(expression){
2. //content to be evaluated if condition is true
3. }
4. else{
5. //content to be evaluated if condition is false
6. }
Flowchart of JavaScript If...else statement

Let’s see the example of if-else statement in JavaScript to find out the even
or odd number.

<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>

avaScript If...else if statement


It evaluates the content only if expression is true from several expressions.
The signature of JavaScript if else if statement is given below.

if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}

Let’s see the simple example of if else if statement in javascript.

<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>

JavaScript Switch
The JavaScript switch statement is used to execute one code from
multiple expressions. It is just like else if statement that we have learned in
previous page. But it is convenient than if..else..if because it can be used
with numbers, characters etc.

The signature of JavaScript switch statement is given below.

Let’s see the simple example of switch statement in javascript.

<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
Day-8
JavaScript while loop
The JavaScript while loop iterates the elements for the infinite number of
times. It should be used if number of iteration is not known. The syntax of
while loop is given below.

while (condition)
{
code to be executed
}

<!DOCTYPE html>
<html>
<body>
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
</body>
</html>
Day-9
JavaScript For loop

A for loop repeats until a specified condition evaluates to false. The


JavaScript for loop is similar to the Java and C for loop.
A for statement looks as follows:
JSCopy to Clipboard
for (initialization; condition; afterthought)
statement
When a for loop executes, the following occurs:
1. The initializing expression initialization, if any, is executed. This expression
usually initializes one or more loop counters, but the syntax allows an
expression of any degree of complexity. This expression can also declare
variables.
2. The condition expression is evaluated. If the value of condition is true, the
loop statements execute. Otherwise, the for loop terminates. (If
the condition expression is omitted entirely, the condition is assumed to be
true.)
3. The statement executes. To execute multiple statements, use a block
statement ({ }) to group those statements.
4. If present, the update expression afterthought is executed.
5. Control returns to Step 2.
Day-10
The JavaScript for loop iterates the elements for the fixed number of
times. It should be used if number of iteration is known. The syntax of for
loop is given below.

for (initialization; condition; increment)


{
code to be executed
}

Let’s see the simple example of for loop in javascript.

<!DOCTYPE html>

<html>

<body>

<script>

for (i=1; i<=5; i++)

document.write(i + "<br/>")

</script>

</body>

</html>
Day-11
Functions
Functions are one of the fundamental building blocks in JavaScript. A function in
JavaScript is similar to a procedure—a set of statements that performs a task or
calculates a value, but for a procedure to qualify as a function, it should take some
input and return an output where there is some obvious relationship between the
input and the output. To use a function, you must define it somewhere in the scope
from which you wish to call it.

Defining functions
Function declarations

A function definition (also called a function declaration, or function statement) consists of


the function keyword, followed by:

 The name of the function.


 A list of parameters to the function, enclosed in parentheses and separated by commas.
 The JavaScript statements that define the function, enclosed in curly braces, { /* … */ }.

For example, the following code defines a simple function named square:

JSCopy to Clipboard
function square(number) {
return number * number;
}

The function square takes one parameter, called number. The function consists of one statement
that says to return the parameter of the function (that is, number) multiplied by itself.
The return statement specifies the value returned by the function, which is number * number.

Parameters are essentially passed to functions by value — so if the code within the body of a
function assigns a completely new value to a parameter that was passed to the function, the
change is not reflected globally or in the code which called that function.

When you pass an object as a parameter, if the function changes the object's properties, that
change is visible outside the function, as shown in the following example:

JSCopy to Clipboard
function myFunc(theObject) {
theObject.make = "Toyota";
}

const mycar = {
make: "Honda",
model: "Accord",
year: 1998,
};

console.log(mycar.make); // "Honda"
myFunc(mycar);
console.log(mycar.make); // "Toyota"

When you pass an array as a parameter, if the function changes any of the array's values, that
change is visible outside the function, as shown in the following example:

JSCopy to Clipboard
function myFunc(theArr) {
theArr[0] = 30;
}

const arr = [45];

console.log(arr[0]); // 45
myFunc(arr);
console.log(arr[0]); // 30
Function expressions

While the function declaration above is syntactically a statement, functions can also be created
by a function expression.

Such a function can be anonymous; it does not have to have a name. For example, the
function square could have been defined as:

JSCopy to Clipboard
const square = function (number) {
return number * number;
};

console.log(square(4)); // 16

However, a name can be provided with a function expression. Providing a name allows the
function to refer to itself, and also makes it easier to identify the function in a debugger's stack
traces:

JSCopy to Clipboard
const factorial = function fac(n) {
return n < 2 ? 1 : n * fac(n - 1);
};

console.log(factorial(3)); // 6
Function expressions are convenient when passing a function as an argument to another function.
The following example shows a map function that should receive a function as first argument
and an array as second argument:

JSCopy to Clipboard
function map(f, a) {
const result = new Array(a.length);
for (let i = 0; i < a.length; i++) {
result[i] = f(a[i]);
}
return result;
}

In the following code, the function receives a function defined by a function expression and
executes it for every element of the array received as a second argument:

JSCopy to Clipboard
function map(f, a) {
const result = new Array(a.length);
for (let i = 0; i < a.length; i++) {
result[i] = f(a[i]);
}
return result;
}

const cube = function (x) {


return x * x * x;
};

const numbers = [0, 1, 2, 5, 10];


console.log(map(cube, numbers)); // [0, 1, 8, 125, 1000]

In JavaScript, a function can be defined based on a condition. For example, the following
function definition defines myFunc only if num equals 0:

JSCopy to Clipboard
let myFunc;
if (num === 0) {
myFunc = function (theObject) {
theObject.make = "Toyota";
};
}

In addition to defining functions as described here, you can also use the Function constructor to
create functions from a string at runtime, much like eval().

A method is a function that is a property of an object. Read more about objects and methods
in Working with objects.
Calling functions

Defining a function does not execute it. Defining it names the function and specifies what to do
when the function is called.

Calling the function actually performs the specified actions with the indicated parameters. For
example, if you define the function square, you could call it as follows:

JSCopy to Clipboard
square(5);

The preceding statement calls the function with an argument of 5. The function executes its
statements and returns the value 25.

Functions must be in scope when they are called, but the function declaration can
be hoisted (appear below the call in the code). The scope of a function declaration is the function
in which it is declared (or the entire program, if it is declared at the top level).

The arguments of a function are not limited to strings and numbers. You can pass whole objects
to a function. The showProps() function (defined in Working with objects) is an example of a
function that takes an object as an argument.

A function can call itself. For example, here is a function that computes factorials recursively:

JSCopy to Clipboard
function factorial(n) {
if (n === 0 || n === 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}

You could then compute the factorials of 1 through 5 as follows:

JSCopy to Clipboard
console.log(factorial(1)); // 1
console.log(factorial(2)); // 2
console.log(factorial(3)); // 6
console.log(factorial(4)); // 24
console.log(factorial(5)); // 120

There are other ways to call functions. There are often cases where a function needs to be called
dynamically, or the number of arguments to a function vary, or in which the context of the
function call needs to be set to a specific object determined at runtime.

It turns out that functions are themselves objects — and in turn, these objects have methods. (See
the Function object.) The call() and apply() methods can be used to achieve this goal.
Function hoisting

Consider the example below:

JSCopy to Clipboard
console.log(square(5)); // 25

function square(n) {
return n * n;
}

This code runs without any error, despite the square() function being called before it's declared.
This is because the JavaScript interpreter hoists the entire function declaration to the top of the
current scope, so the code above is equivalent to:

JSCopy to Clipboard
// All function declarations are effectively at the top of the scope
function square(n) {
return n * n;
}

console.log(square(5)); // 25

Function hoisting only works with function declarations — not with function expressions. The
following code will not work:

JSCopy to Clipboard
console.log(square(5)); // ReferenceError: Cannot access 'square' before initialization
const square = function (n) {
return n * n;
};
Day-12
Function scope

Variables defined inside a function cannot be accessed from anywhere outside the function,
because the variable is defined only in the scope of the function. However, a function can access
all variables and functions defined inside the scope in which it is defined.

In other words, a function defined in the global scope can access all variables defined in the
global scope. A function defined inside another function can also access all variables defined in
its parent function, and any other variables to which the parent function has access.

JSCopy to Clipboard
// The following variables are defined in the global scope
const num1 = 20;
const num2 = 3;
const name = "Chamakh";

// This function is defined in the global scope


function multiply() {
return num1 * num2;
}

console.log(multiply()); // 60

// A nested function example


function getScore() {
const num1 = 2;
const num2 = 3;

function add() {
return `${name} scored ${num1 + num2}`;
}

return add();
}

console.log(getScore()); // "Chamakh scored 5"


Scope and the function stack
Recursion

A function can refer to and call itself. There are three ways for a function to refer to itself:

1. The function's name


2. arguments.callee
3. An in-scope variable that refers to the function

For example, consider the following function definition:


JSCopy to Clipboard
const foo = function bar() {
// statements go here
};

Within the function body, the following are all equivalent:

1. bar()
2. arguments.callee()
3. foo()

A function that calls itself is called a recursive function. In some ways, recursion is analogous to
a loop. Both execute the same code multiple times, and both require a condition (to avoid an
infinite loop, or rather, infinite recursion in this case).

For example, consider the following loop:

JSCopy to Clipboard
let x = 0;
// "x < 10" is the loop condition
while (x < 10) {
// do stuff
x++;
}

It can be converted into a recursive function declaration, followed by a call to that function:

JSCopy to Clipboard
function loop(x) {
// "x >= 10" is the exit condition (equivalent to "!(x < 10)")
if (x >= 10) {
return;
}
// do stuff
loop(x + 1); // the recursive call
}
loop(0);

However, some algorithms cannot be simple iterative loops. For example, getting all the nodes of
a tree structure (such as the DOM) is easier via recursion:

JSCopy to Clipboard
function walkTree(node) {
if (node === null) {
return;
}
// do something with node
for (let i = 0; i < node.childNodes.length; i++) {
walkTree(node.childNodes[i]);
}
}
Compared to the function loop, each recursive call itself makes many recursive calls here.

It is possible to convert any recursive algorithm to a non-recursive one, but the logic is often
much more complex, and doing so requires the use of a stack.

In fact, recursion itself uses a stack: the function stack. The stack-like behavior can be seen in the
following example:

JSCopy to Clipboard
function foo(i) {
if (i < 0) {
return;
}
console.log(`begin: ${i}`);
foo(i - 1);
console.log(`end: ${i}`);
}
foo(3);

// Logs:
// begin: 3
// begin: 2
// begin: 1
// begin: 0
// end: 0
// end: 1
// end: 2
// end: 3
Nested functions and closures

You may nest a function within another function. The nested (inner) function is private to its
containing (outer) function.

It also forms a closure. A closure is an expression (most commonly, a function) that can have
free variables together with an environment that binds those variables (that "closes" the
expression).

Since a nested function is a closure, this means that a nested function can "inherit" the arguments
and variables of its containing function. In other words, the inner function contains the scope of
the outer function.

To summarize:

 The inner function can be accessed only from statements in the outer function.
 The inner function forms a closure: the inner function can use the arguments and variables of
the outer function, while the outer function cannot use the arguments and variables of the inner
function.

The following example shows nested functions:


JSCopy to Clipboard
function addSquares(a, b) {
function square(x) {
return x * x;
}
return square(a) + square(b);
}

console.log(addSquares(2, 3)); // 13
console.log(addSquares(3, 4)); // 25
console.log(addSquares(4, 5)); // 41

Since the inner function forms a closure, you can call the outer function and specify arguments
for both the outer and inner function:

JSCopy to Clipboard
function outside(x) {
function inside(y) {
return x + y;
}
return inside;
}

const fnInside = outside(3); // Think of it like: give me a function that adds 3 to whatever
you give it
console.log(fnInside(5)); // 8
console.log(outside(3)(5)); // 8
Preservation of variables

Notice how x is preserved when inside is returned. A closure must preserve the arguments and
variables in all scopes it references. Since each call provides potentially different arguments, a
new closure is created for each call to outside. The memory can be freed only when the
returned inside is no longer accessible.

This is not different from storing references in other objects, but is often less obvious because
one does not set the references directly and cannot inspect them.

Multiply-nested functions

Functions can be multiply-nested. For example:

 A function (A) contains a function (B), which itself contains a function (C).
 Both functions B and C form closures here. So, B can access A, and C can access B.
 In addition, since C can access B which can access A, C can also access A.

Thus, the closures can contain multiple scopes; they recursively contain the scope of the
functions containing it. This is called scope chaining. (The reason it is called "chaining" is
explained later.)
Consider the following example:

JSCopy to Clipboard
function A(x) {
function B(y) {
function C(z) {
console.log(x + y + z);
}
C(3);
}
B(2);
}
A(1); // Logs 6 (which is 1 + 2 + 3)

In this example, C accesses B's y and A's x.

This can be done because:

1. B forms a closure including A (i.e., B can access A's arguments and variables).
2. C forms a closure including B.
3. Because C's closure includes B and B's closure includes A, then C's closure also includes A. This
means C can access both B and A's arguments and variables. In other words, C chains the
scopes of B and A, in that order.

The reverse, however, is not true. A cannot access C, because A cannot access any argument or
variable of B, which C is a variable of. Thus, C remains private to only B.

Name conflicts

When two arguments or variables in the scopes of a closure have the same name, there is a name
conflict. More nested scopes take precedence. So, the innermost scope takes the highest
precedence, while the outermost scope takes the lowest. This is the scope chain. The first on the
chain is the innermost scope, and the last is the outermost scope. Consider the following:

JSCopy to Clipboard
function outside() {
const x = 5;
function inside(x) {
return x * 2;
}
return inside;
}

console.log(outside()(10)); // 20 (instead of 10)

The name conflict happens at the statement return x * 2 and is between inside's
parameter x and outside's variable x. The scope chain here is {inside, outside, global object}.
Therefore, inside's x takes precedences over outside's x, and 20 (inside's x) is returned instead
of 10 (outside's x).
Closures

Closures are one of the most powerful features of JavaScript. JavaScript allows for the nesting of
functions and grants the inner function full access to all the variables and functions defined
inside the outer function (and all other variables and functions that the outer function has access
to).

However, the outer function does not have access to the variables and functions defined inside
the inner function. This provides a sort of encapsulation for the variables of the inner function.

Also, since the inner function has access to the scope of the outer function, the variables and
functions defined in the outer function will live longer than the duration of the outer function
execution, if the inner function manages to survive beyond the life of the outer function. A
closure is created when the inner function is somehow made available to any scope outside the
outer function.

JSCopy to Clipboard
// The outer function defines a variable called "name"
const pet = function (name) {
const getName = function () {
// The inner function has access to the "name" variable of the outer function
return name;
};
return getName; // Return the inner function, thereby exposing it to outer scopes
};
const myPet = pet("Vivie");

console.log(myPet()); // "Vivie"

It can be much more complex than the code above. An object containing methods for
manipulating the inner variables of the outer function can be returned.

JSCopy to Clipboard
const createPet = function (name) {
let sex;

const pet = {
// setName(newName) is equivalent to setName: function (newName)
// in this context
setName(newName) {
name = newName;
},

getName() {
return name;
},

getSex() {
return sex;
},
setSex(newSex) {
if (
typeof newSex === "string" &&
(newSex.toLowerCase() === "male" || newSex.toLowerCase() === "female")
){
sex = newSex;
}
},
};

return pet;
};

const pet = createPet("Vivie");


console.log(pet.getName()); // Vivie

pet.setName("Oliver");
pet.setSex("male");
console.log(pet.getSex()); // male
console.log(pet.getName()); // Oliver

In the code above, the name variable of the outer function is accessible to the inner functions,
and there is no other way to access the inner variables except through the inner functions. The
inner variables of the inner functions act as safe stores for the outer arguments and variables.
They hold "persistent" and "encapsulated" data for the inner functions to work with. The
functions do not even have to be assigned to a variable, or have a name.

JSCopy to Clipboard
const getCode = (function () {
const apiCode = "0]Eal(eh&2"; // A code we do not want outsiders to be able to modify…

return function () {
return apiCode;
};
})();

console.log(getCode()); // "0]Eal(eh&2"
Note: There are a number of pitfalls to watch out for when using closures!

If an enclosed function defines a variable with the same name as a variable in the outer scope,
then there is no way to refer to the variable in the outer scope again. (The inner scope variable
"overrides" the outer one, until the program exits the inner scope. It can be thought of as a name
conflict.)

JSCopy to Clipboard
const createPet = function (name) {
// The outer function defines a variable called "name".
return {
setName(name) {
// The enclosed function also defines a variable called "name".
name = name; // How do we access the "name" defined by the outer function?
},
};
};
Using the arguments object

The arguments of a function are maintained in an array-like object. Within a function, you can
address the arguments passed to it as follows:

JSCopy to Clipboard
arguments[i];

where i is the ordinal number of the argument, starting at 0. So, the first argument passed to a
function would be arguments[0]. The total number of arguments is indicated
by arguments.length.

Using the arguments object, you can call a function with more arguments than it is formally
declared to accept. This is often useful if you don't know in advance how many arguments will
be passed to the function. You can use arguments.length to determine the number of arguments
actually passed to the function, and then access each argument using the arguments object.

For example, consider a function that concatenates several strings. The only formal argument for
the function is a string that specifies the characters that separate the items to concatenate. The
function is defined as follows:

JSCopy to Clipboard
function myConcat(separator) {
let result = ""; // initialize list
// iterate through arguments
for (let i = 1; i < arguments.length; i++) {
result += arguments[i] + separator;
}
return result;
}

You can pass any number of arguments to this function, and it concatenates each argument into a
string "list":

JSCopy to Clipboard
console.log(myConcat(", ", "red", "orange", "blue"));
// "red, orange, blue, "

console.log(myConcat("; ", "elephant", "giraffe", "lion", "cheetah"));


// "elephant; giraffe; lion; cheetah; "

console.log(myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley"));


// "sage. basil. oregano. pepper. parsley. "
Note: The arguments variable is "array-like", but not an array. It is array-like in that it has a
numbered index and a length property. However, it does not possess all of the array-
manipulation methods.
See the Function object in the JavaScript reference for more information.

Function parameters

There are two special kinds of parameter syntax: default parameters and rest parameters.

Default parameters

In JavaScript, parameters of functions default to undefined. However, in some situations it might


be useful to set a different default value. This is exactly what default parameters do.

In the past, the general strategy for setting defaults was to test parameter values in the body of
the function and assign a value if they are undefined.

In the following example, if no value is provided for b, its value would be undefined when
evaluating a*b, and a call to multiply would normally have returned NaN. However, this is
prevented by the second line in this example:

JSCopy to Clipboard
function multiply(a, b) {
b = typeof b !== "undefined" ? b : 1;
return a * b;
}

console.log(multiply(5)); // 5

With default parameters, a manual check in the function body is no longer necessary. You can
put 1 as the default value for b in the function head:

JSCopy to Clipboard
function multiply(a, b = 1) {
return a * b;
}

console.log(multiply(5)); // 5

For more details, see default parameters in the reference.

Rest parameters

The rest parameter syntax allows us to represent an indefinite number of arguments as an array.

In the following example, the function multiply uses rest parameters to collect arguments from
the second one to the end. The function then multiplies these by the first argument.

JSCopy to Clipboard
function multiply(multiplier, ...theArgs) {
return theArgs.map((x) => multiplier * x);
}

const arr = multiply(2, 1, 2, 3);


console.log(arr); // [2, 4, 6]
Arrow functions

An arrow function expression (also called a fat arrow to distinguish from a hypothetical -
> syntax in future JavaScript) has a shorter syntax compared to function expressions and does
not have its own this, arguments, super, or new.target. Arrow functions are always
anonymous.

Two factors influenced the introduction of arrow functions: shorter functions and non-
binding of this.

Shorter functions

In some functional patterns, shorter functions are welcome. Compare:

JSCopy to Clipboard
const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];

const a2 = a.map(function (s) {


return s.length;
});

console.log(a2); // [8, 6, 7, 9]

const a3 = a.map((s) => s.length);

console.log(a3); // [8, 6, 7, 9]
No separate this

Until arrow functions, every new function defined its own this value (a new object in the case of
a constructor, undefined in strict mode function calls, the base object if the function is called as
an "object method", etc.). This proved to be less than ideal with an object-oriented style of
programming.

JSCopy to Clipboard
function Person() {
// The Person() constructor defines `this` as itself.
this.age = 0;

setInterval(function growUp() {
// In nonstrict mode, the growUp() function defines `this`
// as the global object, which is different from the `this`
// defined by the Person() constructor.
this.age++;
}, 1000);
}
const p = new Person();

In ECMAScript 3/5, this issue was fixed by assigning the value in this to a variable that could be
closed over.

JSCopy to Clipboard
function Person() {
// Some choose `that` instead of `self`.
// Choose one and be consistent.
const self = this;
self.age = 0;

setInterval(function growUp() {
// The callback refers to the `self` variable of which
// the value is the expected object.
self.age++;
}, 1000);
}

Alternatively, a bound function could be created so that the proper this value would be passed to
the growUp() function.

An arrow function does not have its own this; the this value of the enclosing execution context is
used. Thus, in the following code, the this within the function that is passed to setInterval has
the same value as this in the enclosing function:

JSCopy to Clipboard
function Person() {
this.age = 0;

setInterval(() => {
this.age++; // `this` properly refers to the person object
}, 1000);
}

const p = new Person();


Day-13
JavaScript Arrays
Introduction
An array in JavaScript is a type of global object that is used to store data. Arrays
consist of an ordered collection or list containing zero or more data types, and use
numbered indices starting from 0 to access specific items.
Arrays are very useful as they store multiple values in a single variable, which can
condense and organize our code, making it more readable and maintainable. Arrays
can contain any data type, including numbers, strings, and objects.

To demonstrate how arrays can be useful, consider assigning the five oceans of the
world to their own variables.

oceans.js

// Assign the five oceans to five variables


const ocean1 = "Pacific";
const ocean2 = "Atlantic";
const ocean3 = "Indian";
const ocean4 = "Arctic";
const ocean5 = "Antarctic";
Copy

This method is very verbose, and can quickly become difficult to maintain and keep
track of.

Using arrays, we can simplify our data.

oceans.js

// Assign the five oceans


let oceans = [
"Pacific",
"Atlantic",
"Indian",
"Arctic",
"Antarctic",
];
Copy
Instead of creating five separate variables, we now have one variable that contains all
five elements. We used square brackets — [] — to create an array.

To access a specific item, append its index to the variable.

// Print out the first item of the oceans array


oceans[0];
Copy

Output
Pacific

In this tutorial, we will learn how to create arrays; how they are indexed; how to add,
modify, remove, or access items in an array; and how to loop through arrays.
Day-14
Creating an Array

There are two ways to create an array in JavaScript:

 The array literal, which uses square brackets.


 The array constructor, which uses the new keyword.
Let’s demonstrate how to create an array of shark species using the array literal, which
is initialized with [].
// Initialize array of shark species with array literal
[label sharks.js]
let sharks = [
"Hammerhead",
"Great White",
"Tiger",
];
Copy

Now here is the same data created with the array constructor, which is initialized
with new Array().
sharks.js

// Initialize array of shark species with array constructor


let sharks = new Array(
"Hammerhead",
"Great White",
"Tiger",
);
Copy

Both methods will create an array. However, the array literal (square brackets) method
is much more common and preferred, as the new Array() constructor method may
have inconsistencies and unexpected results. It’s useful to be aware of the array
constructor in case you encounter it down the line.

We can print out an entire array, which will display the same as our input.

// Print out the entire sharks array


sharks;
Copy

Output
[ 'Hammerhead', 'Great White', 'Tiger' ]

Arrays are often used to group together lists of similar data types, but they can
technically contain any value or a mix of values, including other arrays.

// Initialize array of mixed datatypes


let mixedData = [
"String",
null,
7,
[
"another",
"array",
],
];
Copy

After creating an array, we can manipulate them in many ways, but first we must
understand how arrays are indexed.

Note: You may see the last item in an array with or without a final comma. This is known as
a trailing comma. It is common to see them omitted, but generally it is becomming preferred
to include them in your code, as this makes version control diffs more clear, and makes it
easier to add and remove items without errors. Note that trailing commas are not allowed
in JSON files.
Day-15
Indexing Arrays
If you’ve learned about indexing and manipulating strings in JavaScript, you may be
familiar with the concept of indexing arrays already, as a string is similar to an array.
Arrays do not have name/value pairs. Instead, they are indexed with integer values
beginning with 0. Here is an example array, assigned to seaCreatures.
seacreatures.js

let seaCreatures = [
"octopus",
"squid",
"shark",
"seahorse",
"starfish",
];
Copy

Here is a breakdown of how each item in the seaCreatures array is indexed.

octopus squid shark seahorse starfish

0 1 2 3 4

The first item in the array is octopus, which is indexed at 0. The last item is starfish,
which is indexed at 4. Counting starts with 0 in indices, which goes against our natural
intuition to start counting at 1, so special care must be taken to remember this until it
becomes natural.
We can find out how many items are in an array with the length property.
seaCreatures.length;
Copy

Output
5
Although the indices of seaCreatures consist of 0 to 4, the length property will output
the actual amount of items in the array, starting with 1.
If we want to find out the index number of a specific item in an array, such as seahorse,
we can use the indexOf() method.
seaCreatures.indexOf("seahorse");
Copy

Output
3
If an index number is not found, such as for a value that does not exist, the console will
return -1.
seaCreatures.indexOf("cuttlefish");
Copy

Output
-1

With index numbers that correspond to items within an array, we’re able to access each
item discretely in order to work with those items.

Accessing Items in an Array

An item in a JavaScript array is accessed by referring to the index number of the item in
square brackets.

seaCreatures[1];
Copy

Output
squid
We know 0 will always output the first item in an array. We can also find the last item in
an array by performing an operation on the length property and applying that as the
new index number.
const lastIndex = seaCreatures.length - 1;

seaCreatures[lastIndex];
Copy

Output
starfish
Attempting to access an item that doesn’t exist will return undefined.
seaCreatures[10];
Copy

Output
undefined

In order to access items in a nested array, you would add another index number to
correspond to the inner array.

let nestedArray = [
[
"salmon",
"halibut",
],
[
"coral",
"reef",
]
];

nestedArray[1][0];
Copy

Output
coral
In the above example, we accessed the array at position 1 of the nestedArray variable,
then the item at position 0 in the inner array.
Adding an Item to an Array
In our seaCreatures variable we had five items, which consisted of the indices
from 0 to 4. If we want to add a new item to the array, we can assign a value to the next
index.
seaCreatures[5] = "whale";

seaCreatures;
Copy

Output
[ 'octopus',
'squid',
'shark',
'seahorse',
'starfish',
'whale' ]

If we add an item and accidentally skip an index, it will create an undefined item in the
array.

seaCreatures[7] = "pufferfish";

seaCreatures;
Copy

Output
[ 'octopus',
'squid',
'shark',
'seahorse',
'starfish',
'whale',
,
'pufferfish' ]
Attempting to access the extra array item will return undefined.
seaCreatures[6]
Copy

Output
undefined
Issues like that can be avoided by using the push() method, which adds an item to the
end of an array.
// Append lobster to the end of the seaCreatures array
seaCreatures.push("lobster");

seaCreatures;
Copy

Output
[ 'octopus',
'squid',
'shark',
'seahorse',
'starfish',
,
'whale',
'pufferfish',
'lobster' ]
On the other end of the spectrum, the unshift() method will add an item to the
beginning of an array.
// Append dragonfish to the beginning of the seaCreatures array
seaCreatures.unshift("dragonfish");

seaCreatures;
Copy

Output
[ 'dragonfish',
'octopus',
'squid',
'shark',
'seahorse',
'starfish',
'whale',
,
'pufferfish',
'lobster' ]
Between push() and unshift() you will be able to apend items to the beginning and
end of an array.
Removing an Item from an Array
When we want to remove a specific item from an array, we use the splice() method.
In the seaCreatures array, we accidentally created an undefined array item earlier, so
let’s remove that now.
seaCreatures.splice(7, 1);

seaCreatures;
Copy

Output
[ 'dragonfish',
'octopus',
'squid',
'shark',
'seahorse',
'starfish',
'whale',
'pufferfish',
'lobster' ]
In the splice() method, the first parameter stands for the index number to be removed
(in this case, 7), and the second parameter is how many items should be removed. We
put 1, signifying that only one item will be removed.
The splice() method will change the original variable. If you would like the original
variable to remain unchanged, use slice() and assign the result to a new variable.
Here we will assign two variables, one that uses slice() to store
the seaCreatures array from the first element until whale, and a second variable to
store the elements pufferfish and lobster. To join the two arrays, we’ll use
the concat() method to return the new array.
let firstArray = seaCreatures.slice(0, 7);
let secondArray = seaCreatures.slice(8, 10);
firstArray.concat(secondArray);
Copy

Output
[ 'dragonfish',
'octopus',
'squid',
'shark',
'seahorse',
'starfish',
'whale',
'pufferfish',
'lobster' ]
Notice that when calling the seaCreatures variable, the items in the array remain
unchanged.
seaCreatures;
Copy

Output
[ 'dragonfish',
'octopus',
'squid',
'shark',
'seahorse',
'starfish',
'whale',
,
'pufferfish',
'lobster' ]
The pop() method will remove the last item in an array.
// Remove the last item from the seaCreatures array
seaCreatures.pop();

seaCreatures;
Copy

Output
[ 'dragonfish',
'octopus',
'squid',
'shark',
'seahorse',
'starfish',
'whale',
'pufferfish' ]
lobster has been removed as the last item of the array. In order to remove the first
item of the array, we will use the shift() method.
// Remove the first item from the seaCreatures array
seaCreatures.shift();

seaCreatures;
Copy

Output
[ 'octopus',
'squid',
'shark',
'seahorse',
'starfish',
'whale',
'pufferfish' ]
By using pop() and shift(), we can remove items from the beginning and the end of
arrays. Using pop() is preferred wherever possible, as the rest of the items in the array
retain their original index numbers.
Modifying Items in Arrays

We can overwrite any value in an array by assigning a new value using the assignment
operator, just like we would with a regular variable.

// Assign manatee to the first item in the seaCreatures array


seaCreatures[0] = "manatee";

seaCreatures;
Copy

Output
[ 'manatee',
'squid',
'shark',
'seahorse',
'starfish',
'whale',
'pufferfish' ]
Another way to modify a value is using the splice() method with a new parameter. If
we wanted to change the value of seahorse, which is the item at index 3, we could
remove it and add a new item in its place.
// Replace seahorse with sea lion using splice method
seaCreatures.splice(3, 1, "sea lion");

seaCreatures();
Copy

Output
[ 'manatee',
'squid',
'shark',
'sea lion',
'starfish',
'whale',
'pufferfish' ]
In the above example, we removed seahorse from the array, and pushed a new value
into index 3.
Looping Through an Array
We can loop through the entirety of the array with the for keyword, taking advantage of
the length property. In this example, we can create an array of shellfish and print out
each index number as well as each value to the console.
// Create an array of shellfish species
let shellfish = [
"oyster",
"shrimp",
"clam",
"mussel",
];

// Loop through the length of the array


for (let i = 0; i < shellfish.length; i++) {
console.log(i, shellfish[i]);
}
Copy

Output
0 'oyster'
1 'shrimp'
2 'clam'
3 'mussel'
We can also use the for...of loop, a newer feature of JavaScript.
// Create an array of aquatic mammals
let mammals = [
"dolphin",
"whale",
"manatee",
];

// Loop through each mammal


for (let mammal of mammals) {
console.log(mammal);
}
Copy

Output
dolphin
whale
manatee
The for...of loop does not retrieve the index number of the elements in the array, but
it is generally a simpler, more concise way to loop through an array.
Day-16
JavaScript Sorting Arrays
Sorting an Array
The sort() method sorts an array alphabetically:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();

Reversing an Array
The reverse() method reverses the elements in an array.

You can use it to sort an array in descending order:

Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();

Numeric Sort
By default, the sort() function sorts values as strings.

This works well for strings ("Apple" comes before "Banana").

However, if numbers are sorted as strings, "25" is bigger than "100", because
"2" is bigger than "1".

Because of this, the sort() method will produce incorrect result when sorting
numbers.

You can fix this by providing a compare function:


Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});

Use the same trick to sort an array descending:

Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});

The Compare Function


The purpose of the compare function is to define an alternative sort order.

The compare function should return a negative, zero, or positive value,


depending on the arguments:

function(a, b){return a - b}

When the sort() function compares two values, it sends the values to the
compare function, and sorts the values according to the returned (negative,
zero, positive) value.

If the result is negative, a is sorted before b.

If the result is positive, b is sorted before a.

If the result is 0, no changes are done with the sort order of the two values.

Example:

The compare function compares all the values in the array, two values at a
time (a, b).

When comparing 40 and 100, the sort() method calls the compare function(40,
100).

The function calculates 40 - 100 (a - b), and since the result is negative (-60),
the sort function will sort 40 as a value lower than 100.
You can use this code snippet to experiment with numerically and alphabetically
sorting:

<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The sort() Method</h2>

<p>Click the buttons to sort the array alphabetically or numerically.</p>

<button onclick="myFunction1()">Sort Alphabetically</button>


<button onclick="myFunction2()">Sort Numerically</button>

<p id="demo"></p>

<script>
const points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;

function myFunction1() {
points.sort();
document.getElementById("demo").innerHTML = points;
}
function myFunction2() {
points.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = points;
}
</script>

</body>
</html>

Sorting an Array in Random Order


Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(){return 0.5 - Math.random()});

The Fisher Yates Method


The above example, array.sort(), is not accurate. It will favor some numbers
over the others.

The most popular correct method, is called the Fisher Yates shuffle, and was
introduced in data science as early as 1938!

In JavaScript the method can be translated to this:

Example
const points = [40, 100, 1, 5, 25, 10];

for (let i = points.length -1; i > 0; i--) {


let j = Math.floor(Math.random() * (i+1));
let k = points[i];
points[i] = points[j];
points[j] = k;
}

Find the Lowest (or Highest)


Array Value
There are no built-in functions for finding the max or min value in an array.

However, after you have sorted an array, you can use the index to obtain the
highest and lowest values.

Sorting ascending:

Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
// now points[0] contains the lowest value
// and points[points.length-1] contains the highest value

Sorting descending:

Example
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
// now points[0] contains the highest value
// and points[points.length-1] contains the lowest value

Sorting a whole array is a very inefficient method if you only want to find the
highest (or lowest) value.

Using Math.max() on an Array


You can use Math.max.apply to find the highest number in an array:
Example
function myArrayMax(arr) {
return Math.max.apply(null, arr);
}

Math.max.apply(null, [1, 2, 3]) is equivalent to Math.max(1, 2, 3).

Using Math.min() on an Array


You can use Math.min.apply to find the lowest number in an array:

Example
function myArrayMin(arr) {
return Math.min.apply(null, arr);
}

Math.min.apply(null, [1, 2, 3]) is equivalent to Math.min(1, 2, 3).

My Min / Max JavaScript Methods


The fastest solution is to use a "home made" method.

This function loops through an array comparing each value with the highest
value found:

Example (Find Max)


function myArrayMax(arr) {
let len = arr.length;
let max = -Infinity;
while (len--) {
if (arr[len] > max) {
max = arr[len];
}
}
return max;
}

This function loops through an array comparing each value with the lowest value
found:

Example (Find Min)


function myArrayMin(arr) {
let len = arr.length;
let min = Infinity;
while (len--) {
if (arr[len] < min) {
min = arr[len];
}
}
return min;
}

Sorting Object Arrays


JavaScript arrays often contain objects:

Example
const cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}
];

Even if objects have properties of different data types, the sort() method can
be used to sort the array.

The solution is to write a compare function to compare the property values:

Example
cars.sort(function(a, b){return a.year - b.year});

Comparing string properties is a little more complex:


Example
cars.sort(function(a, b){
let x = a.type.toLowerCase();
let y = b.type.toLowerCase();
if (x < y) {return -1;}
if (x > y) {return 1;}
return 0;
});

Stable Array sort()


ES2019 revised the Array sort() method.

Before 2019, the specification allowed unstable sorting algorithms such as


QuickSort.

After ES2019, browsers must use a stable sorting algorithm:

When sorting elements on a value, the elements must keep their relative
position to other elements with the same value.

const myArr = [
{name:"X00",price:100 },
{name:"X01",price:100 },
{name:"X02",price:100 },
{name:"X03",price:100 },
{name:"X04",price:110 },
{name:"X05",price:110 },
{name:"X06",price:110 },
{name:"X07",price:110 }
];

In the example above, when sorting on price, the result is not allowed to come
out with the names in an other relative position like this:

X01 100
X03 100
X00 100
X03 100
X05 110
X04 110
X06 110
X07 110
Day-17
What Is an Object?
Objects are key to understanding object-oriented technology. Look around right now
and you'll find many examples of real-world objects: your dog, your desk, your television
set, your bicycle.

Real-world objects share two characteristics: They all have state and behavior. Dogs
have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail).
Bicycles also have state (current gear, current pedal cadence, current speed) and
behavior (changing gear, changing pedal cadence, applying brakes). Identifying the
state and behavior for real-world objects is a great way to begin thinking in terms of
object-oriented programming.

Take a minute right now to observe the real-world objects that are in your immediate
area. For each object that you see, ask yourself two questions: "What possible states
can this object be in?" and "What possible behavior can this object perform?". Make
sure to write down your observations. As you do, you'll notice that real-world objects
vary in complexity; your desktop lamp may have only two possible states (on and off)
and two possible behaviors (turn on, turn off), but your desktop radio might have
additional states (on, off, current volume, current station) and behavior (turn on, turn off,
increase volume, decrease volume, seek, scan, and tune). You may also notice that
some objects, in turn, will also contain other objects. These real-world observations all
translate into the world of object-oriented programming.

Software objects are conceptually similar to real-world objects: they too consist of state
and related behavior. An object stores its state in fields (variables in some programming
languages) and exposes its behavior through methods (functions in some programming
languages). Methods operate on an object's internal state and serve as the primary
mechanism for object-to-object communication. Hiding internal state and requiring all
interaction to be performed through an object's methods is known as data
encapsulation — a fundamental principle of object-oriented programming.

Consider a bicycle, for example:

A bicycle modeled as a software object.

By attributing state (current speed, current pedal cadence, and current gear) and
providing methods for changing that state, the object remains in control of how the
outside world is allowed to use it. For example, if the bicycle only has 6 gears, a method
to change gears could reject any value that is less than 1 or greater than 6.

Bundling code into individual software objects provides a number of benefits, including:

1. Modularity: The source code for an object can be written and maintained
independently of the source code for other objects. Once created, an object can
be easily passed around inside the system.
2. Information-hiding: By interacting only with an object's methods, the details of its
internal implementation remain hidden from the outside world.
3. Code re-use: If an object already exists (perhaps written by another software
developer), you can use that object in your program. This allows specialists to
implement/test/debug complex, task-specific objects, which you can then trust to
run in your own code.
4. Pluggability and debugging ease: If a particular object turns out to be
problematic, you can simply remove it from your application and plug in a
different object as its replacement. This is analogous to fixing mechanical
problems in the real world. If a bolt breaks, you replace it, not the entire machine.
Day-18
Class & Object
n the real world, you'll often find many individual objects all of the same kind. There may
be thousands of other bicycles in existence, all of the same make and model. Each
bicycle was built from the same set of blueprints and therefore contains the same
components. In object-oriented terms, we say that your bicycle is an instance of
the class of objects known as bicycles. A class is the blueprint from which individual
objects are created.

The following Bicycle class is one possible implementation of a bicycle:

class Bicycle {

int cadence = 0;
int speed = 0;
int gear = 1;

void changeCadence(int newValue) {


cadence = newValue;
}

void changeGear(int newValue) {


gear = newValue;
}

void speedUp(int increment) {


speed = speed + increment;
}

void applyBrakes(int decrement) {


speed = speed - decrement;
}

void printStates() {
System.out.println("cadence:" +
cadence + " speed:" +
speed + " gear:" + gear);
}
}
The syntax of the Java programming language will look new to you, but the design of
this class is based on the previous discussion of bicycle objects. The
fields cadence, speed, and gear represent the object's state, and the methods
(changeCadence, changeGear, speedUp etc.) define its interaction with the outside
world.

You may have noticed that the Bicycle class does not contain a main method. That's
because it's not a complete application; it's just the blueprint for bicycles that might
be used in an application. The responsibility of creating and using
new Bicycle objects belongs to some other class in your application.

Here's a BicycleDemo class that creates two separate Bicycle objects and invokes
their methods:

class BicycleDemo {
public static void main(String[] args) {

// Create two different


// Bicycle objects
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();

// Invoke methods on
// those objects
bike1.changeCadence(50);
bike1.speedUp(10);
bike1.changeGear(2);
bike1.printStates();

bike2.changeCadence(50);
bike2.speedUp(10);
bike2.changeGear(2);
bike2.changeCadence(40);
bike2.speedUp(10);
bike2.changeGear(3);
bike2.printStates();
}
}

The output of this test prints the ending pedal cadence, speed, and gear for the two
bicycles:

cadence:50 speed:10 gear:2


cadence:40 speed:20 gear:3
Day-19
JavaScript String
The JavaScript string is an object that represents a sequence of characters.

There are 2 ways to create string in JavaScript

1. By string literal
2. By string object (using new keyword)

1) By string literal
The string literal is created using double quotes. The syntax of creating
string using string literal is given below:

var stringname="string value";

Let's see the simple example of creating string literal.

<script>
var str="This is string literal";
document.write(str);
</script>
Day-20
JavaScript String Methods
String length String trim()
String slice() String trimStart()
String substring() String trimEnd()
String substr() String padStart()
String replace() String padEnd()
String replaceAll() String charAt()
String toUpperCase() String charCodeAt()
String toLowerCase() String split()
String concat()

Note
String search methods are covered in the next chapter.

JavaScript String Length


The length property returns the length of a string:

Example
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;

Extracting String Parts


There are 3 methods for extracting a part of a string:

 slice(start, end)
 substring(start, end)
 substr(start, length)
JavaScript String slice()
slice() extracts a part of a string and returns the extracted part in a new string.

The method takes 2 parameters: start position, and end position (end not
included).

Example
Slice out a portion of a string from position 7 to position 13:

let text = "Apple, Banana, Kiwi";


let part = text.slice(7, 13);

Note
JavaScript counts positions from zero.

First position is 0.

Second position is 1.

Examples
If you omit the second parameter, the method will slice out the rest of the
string:

let text = "Apple, Banana, Kiwi";


let part = text.slice(7);

JavaScript String substring()


substring() is similar to slice().

The difference is that start and end values less than 0 are treated as 0
in substring().

Example
let str = "Apple, Banana, Kiwi";
let part = str.substring(7, 13);

If you omit the second parameter, substring() will slice out the rest of the string.
JavaScript String substr()
substr() is similar to slice().

The difference is that the second parameter specifies the length of the
extracted part.

Example
let str = "Apple, Banana, Kiwi";
let part = str.substr(7, 6);

If you omit the second parameter, substr() will slice out the rest of the string.

Example
let str = "Apple, Banana, Kiwi";
let part = str.substr(7);

If the first parameter is negative, the position counts from the end of the string.

Example
let str = "Apple, Banana, Kiwi";
let part = str.substr(-4);

Replacing String Content


The replace() method replaces a specified value with another value in a string:

Example
let text = "Please visit Microsoft!";
let newText = text.replace("Microsoft", "W3Schools");

JavaScript String ReplaceAll()


In 2021, JavaScript introduced the string method replaceAll():
Example
text = text.replaceAll("Cats","Dogs");
text = text.replaceAll("cats","dogs");

The replaceAll() method allows you to specify a regular expression instead of a


string to be replaced.

If the parameter is a regular expression, the global flag (g) must be set,
otherwise a TypeError is thrown.

Example
text = text.replaceAll(/Cats/g,"Dogs");
text = text.replaceAll(/cats/g,"dogs");

Note
replaceAll() is an ES2021 feature.

replaceAll() does not work in Internet Explorer.

Converting to Upper and Lower


Case
A string is converted to upper case with toUpperCase():

A string is converted to lower case with toLowerCase():

JavaScript String toUpperCase()


Example
let text1 = "Hello World!";
let text2 = text1.toUpperCase();
JavaScript String toLowerCase()
Example
let text1 = "Hello World!"; // String
let text2 = text1.toLowerCase(); // text2 is text1 converted to
lower

JavaScript String concat()


concat() joins two or more strings:

Example
let text1 = "Hello";
let text2 = "World";
let text3 = text1.concat(" ", text2);

The concat() method can be used instead of the plus operator. These two lines
do the same:

Example
text = "Hello" + " " + "World!";
text = "Hello".concat(" ", "World!");

Note
All string methods return a new string. They don't modify the original string.

Formally said:

Strings are immutable: Strings cannot be changed, only replaced.

JavaScript String trim()


The trim() method removes whitespace from both sides of a string:
Example
let text1 = " Hello World! ";
let text2 = text1.trim();

JavaScript String trimStart()


ECMAScript 2019 added the String method trimStart() to JavaScript.

The trimStart() method works like trim(), but removes whitespace only from
the start of a string.

Example
let text1 = " Hello World! ";
let text2 = text1.trimStart();
Day-21
JavaScript Get Date Methods
The new Date() Constructor
In JavaScript, date objects are created with new Date().

new Date() returns a date object with the current date and time.

Get the Current Time


const date = new Date();

Date Get Methods


Method Description

getFullYear() Get year as a four digit number (yyyy)

getMonth() Get month as a number (0-11)

getDate() Get day as a number (1-31)

getDay() Get weekday as a number (0-6)

getHours() Get hour (0-23)


getMinutes() Get minute (0-59)

getSeconds() Get second (0-59)

getMilliseconds() Get millisecond (0-999)

getTime() Get time (milliseconds since January 1, 1970)

Note 1
The get methods above return Local time.

Universal time (UTC) is documented at the bottom of this page.

Note 2
The get methods return information from existing date objects.

In a date object, the time is static. The "clock" is not "running".

The time in a date object is NOT the same as current time.

The getFullYear() Method


The getFullYear() method returns the year of a date as a four digit number:

Examples
const d = new Date("2021-03-25");
d.getFullYear();
const d = new Date();
d.getFullYear();
Day-22
JavaScript Events
HTML events are "things" that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can "react" on these


events.

HTML Events
An HTML event can be something the browser does, or something a user does.

Here are some examples of HTML events:

 An HTML web page has finished loading


 An HTML input field was changed
 An HTML button was clicked

Often, when events happen, you may want to do something.

JavaScript lets you execute code when events are detected.

HTML allows event handler attributes, with JavaScript code, to be added to


HTML elements.

With single quotes:

<element event='some JavaScript'>

With double quotes:

<element event="some JavaScript">

In the following example, an onclick attribute (with code), is added to


a <button> element:
Example
<button onclick="document.getElementById('demo').innerHTML =
Date()">The time is?</button>

In the example above, the JavaScript code changes the content of the element
with id="demo".

In the next example, the code changes the content of its own element
(using this.innerHTML):

Example
<button onclick="this.innerHTML = Date()">The time is?</button>

JavaScript code is often several lines long. It is more common to see event
attributes calling functions:

Example
<button onclick="displayDate()">The time is?</button>

Common HTML Events


Here is a list of some common HTML events:

Event Description

onchange An HTML element has been changed

onclick The user clicks an HTML element


onmouseover The user moves the mouse over an HTML element

onmouseout The user moves the mouse away from an HTML element

onkeydown The user pushes a keyboard key

onload The browser has finished loading the page

JavaScript Event Handlers


Event handlers can be used to handle and verify user input, user actions, and
browser actions:

 Things that should be done every time a page loads


 Things that should be done when the page is closed
 Action that should be performed when a user clicks a button
 Content that should be verified when a user inputs data
 And more ...

Many different methods can be used to let JavaScript work with events:

 HTML event attributes can execute JavaScript code directly


 HTML event attributes can call JavaScript functions
 You can assign your own event handler functions to HTML elements
 You can prevent events from being sent or being handled
 And more ...

You will learn a lot more about events and event handlers in the HTML DOM
chapters.
Day-23
AngularJS Introduction
AngularJS is a JavaScript framework. It can be added to an HTML page
with a <script> tag.

AngularJS extends HTML attributes with Directives, and binds data to HTML
with Expressions.

AngularJS is a JavaScript
Framework
AngularJS is a JavaScript framework written in JavaScript.

AngularJS is distributed as a JavaScript file, and can be added to a web page


with a script tag:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/
1.6.9/angular.min.js"></script>

AngularJS Extends HTML


AngularJS extends HTML with ng-directives.

The ng-app directive defines an AngularJS application.

The ng-model directive binds the value of HTML controls (input, select,
textarea) to application data.

The ng-bind directive binds application data to the HTML view.


AngularJS Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/
angular.min.js"></script>
<body>

<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
</div>

</body>
</html>

Example explained:

AngularJS starts automatically when the web page has loaded.

The ng-app directive tells AngularJS that the <div> element is the "owner" of
an AngularJS application.

The ng-model directive binds the value of the input field to the application
variable name.

The ng-bind directive binds the content of the <p> element to the application
variable name.
Day-24

AngularJS Directives
As you have already seen, AngularJS directives are HTML attributes with
an ng prefix.

The ng-init directive initializes AngularJS application variables.

AngularJS Example
<div ng-app="" ng-init="firstName='John'">

<p>The name is <span ng-bind="firstName"></span></p>

</div>

Alternatively with valid HTML:

AngularJS Example
<div data-ng-app="" data-ng-init="firstName='John'">

<p>The name is <span data-ng-bind="firstName"></span></p>

</div>

AngularJS Expressions
AngularJS expressions are written inside double braces: {{ expression }}.

AngularJS will "output" data exactly where the expression is written:

AngularJS Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/
angular.min.js"></script>
<body>

<div ng-app="">
<p>My first expression: {{ 5 + 5 }}</p>
</div>

</body>
</html>

AngularJS expressions bind AngularJS data to HTML the same way as the ng-
bind directive.

AngularJS Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/
angular.min.js"></script>
<body>

<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p>{{name}}</p>
</div>

</body>
</html>
Day-25
AngularJS ng-model Directive
The ng-model directive binds the value of HTML controls (input, select,
textarea) to application data.

The ng-model Directive


With the ng-model directive you can bind the value of an input field to a variable
created in AngularJS.

Example
<div ng-app="myApp" ng-controller="myCtrl">
Name: <input ng-model="name">
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "John Doe";
});
</script>

Two-Way Binding
The binding goes both ways. If the user changes the value inside the input field,
the AngularJS property will also change its value:

Example
<div ng-app="myApp" ng-controller="myCtrl">
Name: <input ng-model="name">
<h1>You entered: {{name}}</h1>
</div>

Validate User Input


The ng-model directive can provide type validation for application data (number,
e-mail, required):

Example
<form ng-app="" name="myForm">
Email:
<input type="email" name="myAddress" ng-model="text">
<span ng-show="myForm.myAddress.$error.email">Not a valid e-mail
address</span>
</form>

In the example above, the span will be displayed only if the expression in
the ng-show attribute returns true.

If the property in the ng-model attribute does not exist, AngularJS will create one
for you.

Application Status
The ng-model directive can provide status for application data (valid, dirty,
touched, error):

Example
<form ng-app="" name="myForm" ng-init="myText = '[email protected]'">
Email:
<input type="email" name="myAddress" ng-model="myText" required>
<h1>Status</h1>
{{myForm.myAddress.$valid}}

{{myForm.myAddress.$dirty}}
{{myForm.myAddress.$touched}}
</form>
CSS Classes
The ng-model directive provides CSS classes for HTML elements, depending on
their status:

Example
<style>
input.ng-invalid {
background-color: lightblue;
}

</style>
<body>

<form ng-app="" name="myForm">


Enter your name:
<input name="myName" ng-model="myText" required>
</form>

The ng-model directive adds/removes the following classes, according to the


status of the form field:

 ng-empty
 ng-not-empty
 ng-touched
 ng-untouched
 ng-valid
 ng-invalid
 ng-dirty
 ng-pending
 ng-pristine
Data binding in AngularJS is the synchronization between the model and the
view.

Data Model
AngularJS applications usually have a data model. The data model is a collection
of data available for the application.

Example
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstname = "John";
$scope.lastname = "Doe";
});

HTML View
The HTML container where the AngularJS application is displayed, is called the
view.

The view has access to the model, and there are several ways of displaying
model data in the view.

You can use the ng-bind directive, which will bind the innerHTML of the element
to the specified model property:

Example
<p ng-bind="firstname"></p>

You can also use double braces {{ }} to display content from the model:

Example
<p>First name: {{firstname}}</p>
Or you can use the ng-model directive on HTML controls to bind the model to the
view.

The ng-model Directive


Use the ng-model directive to bind data from the model to the view on HTML
controls (input, select, textarea)

Example
<input ng-model="firstname">

The ng-model directive provides a two-way binding between the model and the
view.

Two-way Binding
Data binding in AngularJS is the synchronization between the model and the
view.

When data in the model changes, the view reflects the change, and when data
in the view changes, the model is updated as well. This happens immediately
and automatically, which makes sure that the model and the view is updated at
all times.

Example
<div ng-app="myApp" ng-controller="myCtrl">
Name: <input ng-model="firstname">
<h1>{{firstname}}</h1>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstname = "John";
$scope.lastname = "Doe";
});
</script>

AngularJS Controller
Applications in AngularJS are controlled by controllers. Read about controllers in
the AngularJS Controllers chapter.

Because of the immediate synchronization of the model and the view, the
controller can be completely separated from the view, and simply concentrate
on the model data. Thanks to the data binding in AngularJS, the view will reflect
any changes made in the controller.

Example
<div ng-app="myApp" ng-controller="myCtrl">
<h1 ng-click="changeName()">{{firstname}}</h1>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstname = "John";
$scope.changeName = function() {
$scope.firstname = "Nelly";
}
});

</script>
Day-26
AngularJS Filters
Filters can be added in AngularJS to format data.

AngularJS Filters
AngularJS provides filters to transform data:

 currency Format a number to a currency format.


 date Format a date to a specified format.
 filter Select a subset of items from an array.
 json Format an object to a JSON string.
 limitTo Limits an array/string, into a specified number of
elements/characters.
 lowercase Format a string to lower case.
 number Format a number to a string.
 orderBy Orders an array by an expression.
 uppercase Format a string to upper case.

Adding Filters to Expressions


Filters can be added to expressions by using the pipe character |, followed by a
filter.

The uppercase filter format strings to upper case:

Example
<div ng-app="myApp" ng-controller="personCtrl">

<p>The name is {{ lastName | uppercase }}</p>

</div>
The lowercase filter format strings to lower case:

Example
<div ng-app="myApp" ng-controller="personCtrl">

<p>The name is {{ lastName | lowercase }}</p>

</div>

Adding Filters to Directives


Filters are added to directives, like ng-repeat, by using the pipe character |,
followed by a filter:

Example
The orderBy filter sorts an array:

<div ng-app="myApp" ng-controller="namesCtrl">

<ul>
<li ng-repeat="x in names | orderBy:'country'">
{{ x.name + ', ' + x.country }}
</li>
</ul>

</div>

The currency Filter


The currency filter formats a number as currency:

Example
<div ng-app="myApp" ng-controller="costCtrl">

<h1>Price: {{ price | currency }}</h1>

</div>
The filter Filter
The filter filter selects a subset of an array.

The filter filter can only be used on arrays, and it returns an array containing
only the matching items.

Example
Return the names that contains the letter "i":

<div ng-app="myApp" ng-controller="namesCtrl">

<ul>
<li ng-repeat="x in names | filter : 'i'">
{{ x }}
</li>
</ul>

</div>

Filter an Array Based on User


Input
By setting the ng-model directive on an input field, we can use the value of the
input field as an expression in a filter.

Type a letter in the input field, and the list will shrink/grow depending on the
match:

 Jani

 Carl

 Margareth
 Hege

 Joe

 Gustav

 Birgit

 Mary

 Kai

Example
<div ng-app="myApp" ng-controller="namesCtrl">

<p><input type="text" ng-model="test"></p>

<ul>
<li ng-repeat="x in names | filter : test">
{{ x }}
</li>
</ul>

</div>

Sort an Array Based on User Input


Click the table headers to change the sort order::

Name Country

Jani Norway

Carl Sweden
Margareth England

Hege Norway

Joe Denmark

Gustav Sweden

Birgit Denmark

Mary England

Kai Norway

By adding the ng-click directive on the table headers, we can run a function
that changes the sorting order of the array:

Example
<div ng-app="myApp" ng-controller="namesCtrl">

<table border="1" width="100%">


<tr>
<th ng-click="orderByMe('name')">Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr ng-repeat="x in names | orderBy:myOrderBy">
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>

</div>

<script>
angular.module('myApp',
[]).controller('namesCtrl', function($scope) {
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Carl',country:'Sweden'},
{name:'Margareth',country:'England'},
{name:'Hege',country:'Norway'},
{name:'Joe',country:'Denmark'},
{name:'Gustav',country:'Sweden'},
{name:'Birgit',country:'Denmark'},
{name:'Mary',country:'England'},
{name:'Kai',country:'Norway'}
];
$scope.orderByMe = function(x) {
$scope.myOrderBy = x;
}
});
</script>

Custom Filters
You can make your own filters by registering a new filter factory function with
your module:

Example
Make a custom filter called "myFormat":

<ul ng-app="myApp" ng-controller="namesCtrl">


<li ng-repeat="x in names">
{{x | myFormat}}
</li>
</ul>

<script>
var app = angular.module('myApp', []);
app.filter('myFormat', function() {
return function(x) {
var i, c, txt = "";
for (i = 0; i < x.length; i++) {
c = x[i];
if (i % 2 == 0) {
c = c.toUpperCase();
}
txt += c;
}
return txt;
};
});
app.controller('namesCtrl', function($scope) {
$scope.names =
['Jani', 'Carl', 'Margareth', 'Hege', 'Joe', 'Gustav', 'Birgit', 'M
ary', 'Kai'];
});
</script>

You might also like