[Go to site: main page, start]

0% found this document useful (0 votes)
18 views62 pages

JavaScript Basics and Syntax Guide

The document provides a comprehensive overview of JavaScript, covering its syntax, variables, operators, data types, events, and string methods. It explains how to use JavaScript within HTML, the structure of JavaScript statements, and the various types of operators available. Additionally, it details the use of regular expressions and string manipulation methods, emphasizing best practices and the dynamic nature of JavaScript variables.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views62 pages

JavaScript Basics and Syntax Guide

The document provides a comprehensive overview of JavaScript, covering its syntax, variables, operators, data types, events, and string methods. It explains how to use JavaScript within HTML, the structure of JavaScript statements, and the various types of operators available. Additionally, it details the use of regular expressions and string manipulation methods, emphasizing best practices and the dynamic nature of JavaScript variables.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JavaScript

How can use JavaScript in code?


A. JavaScript code use between <script> ….. </script> tag.
<script> [Link] (“hello world”) </script>
B. Old JavaScript may use a type attribute: <script type="text/javascript">. Attribute is not required
now. JavaScript is the default scripting language in HTML.
C. You can place any number of scripts in an HTML document.
D. Scripts can be placed in the <body> or in the <head> section of an HTML page, or in both.
E. Placing scripts at the bottom of the <body> element improves the display speed, because script
interpretation slows down the display.
F. For using external script file, file name uses in src (source) attribute of a <script> tag:
<script src="[Link]"> </scrip>
G. External script files cannot contain <script> tags.

JavaScript Output:
1. Writing into an HTML element, using innerHTML.
2. Writing into the HTML output using [Link]().
** Using [Link]() after an HTML document is loaded, will delete all existing HTML:
3. Writing into an alert box, using [Link]().
4. Writing into the browser console, using [Link]().
JavaScript Statements:
1. JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.

2. Semicolons separate JavaScript statements.


3. JavaScript statements can be grouped together in code blocks, inside curly brackets {…}.
let x, y, z; // Statement 1

JavaScript Syntax
A. JavaScript Values: The JavaScript syntax defines two types of values:
1. Fixed values (Literal)
 Numbers are written with or without decimals: ---------- 10, 10.58
 Strings are text, written within double or single quotes. ---------- “shuvo”
2. Variable values (Variables)
 variables are used to store data values.
 JavaScript uses the keywords var, let and const to declare variables.
 An equal sign is used to assign values to variables
 All JavaScript identifiers are case sensitive.
 Hyphens are not allowed in JavaScript. They are reserved for subtractions.
B. JavaScript Operators: JavaScript uses arithmetic operators ( + - * / ) to compute values.
C. JavaScript Expressions: An expression is a combination of values, variables, and operators,
which computes to a value.
D. JavaScript Keywords: JavaScript keywords are used to identify actions to be performed
E. JavaScript Comments: Code after double slashes // or between /* and */ is treated as a
comment.
F. JavaScript Character Set: JavaScript uses the Unicode character set.
JavaScript Variables
1. Variables are containers for storing data (storing data values).
2. All JavaScript variables must be identified with unique names.
3. These unique names are called identifiers.
4. JavaScript identifiers are case-sensitive.
5. It's a good programming practice to declare all variables at the beginning of a script.
1. var
2. let
3. const
4. nothing

Let:
1. If you think the value of the variable can change, use let.
2. Variables defined with let cannot be re-declared in same block.
3. Variables defined with let must be declared before use.
4. Variables defined with let have Block Scope.
Code:
let x = 5;
let y = 6;
let z = x + y;

Const:
1. If you want a general rule: always declare variables with const
2. Variables defined with const cannot be Re-declared.
3. Variables defined with const cannot be reassigned.
4. Variables defined with const have Block Scope.
5. JavaScript const variables must be assigned a value when they are declared:
6. Use const when you declare:
1. A new Array
2. A new Object
3. A new Function
4. A new RegExp

The keyword const is a little misleading. It does not define a constant value. It defines a constant
reference to a value.

You can NOT:


1. Reassign a constant value
2. Reassign a constant array
3. Reassign a constant object

You CAN:
1. Change the elements of constant array
2. Change the properties of constant object

Value = undefined:
Variables are often declared without a value. The value can be something that has to be calculated,
or something that will be provided later, like user input. A variable declared without a value will have
the value undefined.

JavaScript Operators

Arithmetic Operators: Arithmetic operators perform arithmetic on numbers (literals or variables).


Code:
let x = (100 + 50) * a;

List of Arithmetic Operator:


1. Addition (+)
2. Subtraction (-)
3. Multiplication (*)
4. Exponentiation ( **)
5. Division ( / )
6. Modulus (Remainder) (%)
7. Increment (++ )
8. Decrement (--)

Assignment Operators: Assignment operators assign values to JavaScript variables.

Operator Example Same As


= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y

Shift Assignment Operators:

Operator Example Same As


<<= x <<= y x = x << y
>>= x >>= y x = x >> y
>>>= x >>>= y x = x >>> y

Bitwise Assignment Operators:

Operator Example Same As


&= x &= y x=x&y
^= x ^= y x=x^y
|= x |= y x=x|y
Comparison Operators:

Operato Description
r
== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator

Logical Operators:

Operator Example Same As


&&= x &&= y x = x && (x = y)
||= x ||= y x = x || (x = y)
??= x ??= y x = x?? (x = y)

Conditional/Ternary Operators: JavaScript also contains a conditional operator that assigns a value
to a variable based on some condition.

Variable_name = (condition) ? value1:value2

Type Operators:

typeof Returns the type of a variable

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

Data Types
1. JavaScript variables can hold different data types: numbers, strings, objects.
2. JavaScript evaluates expressions from left to right. Different sequences can produce
different results:
3. JavaScript has dynamic types. This means that the same variable can be used to hold
different data types.

let x; // Now x is undefined


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

Types of data type:

1. Number
2. String
3. Boolean
4. Object
5. Undefined
6. Function
7. bigInt
8. Symbol

The typeof Operator:

typeof "John" // Returns "string"


typeof 3.14 // Returns "number"
typeof NaN // Returns "number"
typeof false // Returns "boolean"
typeof [1,2,3,4] // Returns "object"
typeof {name:'John', age:34} // Returns "object"
typeof new Date() // Returns "object"
typeof function () {} // Returns "function"
typeof myCar // Returns "undefined" *
typeof null // Returns "object"

Type Conversion:

JavaScript Events
1. HTML events are "things" that happen to HTML elements.
2. When JavaScript is used in HTML pages, JavaScript can "react" on these events.
3. An HTML event can be something the browser does, or something a user does.

Here are some examples of HTML events:


1. An HTML web page has finished loading
2. An HTML input field was changed
3. An HTML button was clicked

Common HTML Events


1. Onchange: An HTML element has been changed
2. Onclick: The user clicks an HTML element
3. Onmouseover: The user moves the mouse over an HTML element
4. Onmouseout: The user moves the mouse away from an HTML element
5. Onkeydown: The user pushes a keyboard key
6. Onload: The browser has finished loading the page

Strings
1. A JavaScript string is zero or more characters written inside quotes.
2. You can use single or double quotes
3. You can use quotes inside a string, if they don't match the quotes surrounding the string
4. JavaScript strings are primitive values, created from literals:
5. Strings can also be defined as objects with the keyword new. Do not create Strings objects.
6. Comparing two JavaScript objects always returns false.

Escape Character:
1. \’ ' Single quote
2. \" “ Double quote
3. \\ \ Backslash
4. \b Backspace
5. \f Form Feed
6. \n New Line
7. \r Carriage Return
8. \t Horizontal Tabulator
9. \v Vertical Tabulator

String Methods:
1. All string methods return a new string. They don't modify the original string.
2. Strings are immutable: Strings cannot be changed, only replaced.

1. Length: The length property returns the length of a string:


let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = [Link];

2. slice (start, end):


 Extracts a part of a string.
 String first position is 0. Second position is 1.
 If a parameter is negative, the position is counted from the end of the string.
Syntax: slice (start, end)
start: start position. It includes position.
end: end position. It excludes position.
Code:
let text = "01213456789";
let part = [Link](2, 5);
Ans: 234

3. substring (start, end):


 The substring() method extracts characters from start to end (exclusive).
 The difference is that start and end values less than 0 are treated as 0 .
 If you omit the second parameter, substring () will slice out the rest of the string.
 If start is greater than end, arguments are swapped: (4, 1) = (1, 4).

Syntax : slice(start, end)


start : start position. It includes position.
end : end position. It excludes position.
Code:
let text = "01213456789";
let part = [Link](-2, 5);
Ans: 234
4. substr (start, length):
 second parameter specifies the length of the extracted part.
 If you omit the second parameter, substr () will slice out the rest of the string.
 If the first parameter is negative, the position counts from the end of the string.

Syntax: [Link](start, length);


Start - Required. The start position(index). First character is at index 0.
Length - Optional. The number of characters to extract
Code:
let text = “Pythonworld";
let s = [Link](0, 2);
if( s = “Py” ){
[Link](s);
}
Ans: Py
5. replace ():
 The replace () method replaces a specified value with another value in a string.
 The replace () method does not change the string it is called on.
 The replace () method returns a new string.
 The replace () method replaces only the first match.
 the replace () method is case sensitive

Syntax: [Link]( searchValue, newValue)


searchValue : Required. The value, or regular expression, to search for.
newValue :- Required. The new value (to replace with).

Code:
let text = “Pythonworld";
let s = [Link](/wo/gi , "red");
if( s = “Py” ){
[Link](s);
}
Ans: Py

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


7. toLowerCase (): A string is converted to lower case with toLowerCase ()
8. concat():
 joins two or more strings.
 can be used instead of the plus operator. These two lines do the same.
Code:
let n = “hello ";
let m = “world “;
let s = concat (n, m);
[Link](s);

9. trim (): The trim() method removes whitespace from both sides of a string:
10. trimStart(): removes whitespace only from the start of a string.
11. trimEnd() : removes whitespace only from the end of a string.
12. padEnd(): pads a string with another string:
13. charAt(): The charAt() method returns the character at a specified index (position) in a string.
Code :
let text = "HELLO WORLD";
let letter = [Link](1);

14. split() : A string can be converted to an array with the split() method:
code:
let text = "hello world ";
const myArray = [Link](“ ”);
[Link](myArray[0]);

let text = "hello, world , number ";


const myArray = [Link](“,”);
[Link]("demo").innerHTML = myArray[0];

15. repeat(): The repeat() method returns a string with several copies of a string.

Syntax : [Link](count)
Code :
let text = "Hello world!";
let result = [Link](4)

16. indexOf()
17. lastIndexOf()
18. search ()
19. match ()
20. matchAll()
21. includes ()
22. startsWith()
23. endsWith()

RegX
1. A regular expression is a sequence of characters that forms a search pattern.
2. regular expressions are often used with the two string methods: search() and replace().

Create a RegEx: There are two ways you can create a regular expression in JavaScript.
1. Using a regular expression literal: The regular expression consists of a pattern enclosed
between slashes /…/
cost regularExp = /abc/;
2. Using the RegExp() constructor function: You can also create a regular expression by calling
the RegExp() constructor function. For
const reguarExp = new RegExp('abc', “m”);
Modifiers:
1. i - Perform case-insensitive matching
2. g - Perform a global match (find all matches rather than stopping after the first match)
3. m - Perform multiline matching

Regular Expression Patterns:


Square brackets [] – check every character of string with every character of pattern.

Code:
Var x = “abc hellowqorl”;
Var reg = /[abc]/;
Var y = [Link](x);
1. [a-e] = specify a range of character using – inside square bracket.
2. [^a-g] = with all string expect the character in square bracket.

Period( . ) - A period matches any single character (except newline '\n').


Caret ( ^ ) - used to check if a string starts with a certain character.
Dollar ( $ ) - used to check if a string ends with a certain character.
Star ( * ) – matches zero or more occurrences of the pattern left to it.
Plus (+) - matches one or more occurrences of the pattern left to it.
Question Mark (?) - matches zero or one occurrence of the pattern left to it.
Braces ( {} ) - {n,m}. This means at least n, and at most m repetitions of the pattern left to it.
Alternation ( | ) - Vertical bar | is used for alternation (or operator).
Group ( () ) - Parentheses () is used to group sub-patterns.
Backslash ( \ ) - Backslash \ is used to escape various characters including all metacharacters.
test(): test() method we can check expression are in word or not. If true then return true.
Code :

let str = "HELLO WORLD";


let letter = (/a...b/).test(str)

Template Literals
A. Back-Tics Syntax: Template Literals use back-ticks (``) rather than the quotes ("") to define a
string:
let text = `He's often called "Johnny"`;
let text =`The quick
brown fox
jumps over
the lazy dog`;
B. Interpolation: Template literals provide an easy way to interpolate variables and expressions
into strings.
The syntax is: ${...}
let firstName = "John";
let lastName = "Doe";
let text = `Welcome ${firstName}, ${lastName}!` ;

C. tagged template literals ----------------- (ES6)


1. Tags allow you to parse template literals with a function.
2. The first argument of a tag function contains an array of string values.
3. The remaining arguments are related to the expressions.

Syntax:
TYPICAL FUNCTION
function greet (string, …values) {
// do something
};
TAG FUNCTION
greet ` I 'm ${name} . I'm ${age} years old. `

Example:
function myTag(strings, personExp, ageExp) {
const str0 = strings[0]; // "That "
const str1 = strings[1]; // " is a "
const str2 = strings[2]; // "."
const ageStr = ageExp > 99 ? "Centenarian”: "youngster";
}
const output = myTag `That ${person} is a ${age}. `;

JavaScript Numbers
1. JavaScript Numbers are Always 64-bit Floating Point
2. Integers (numbers without a period or exponent notation) are accurate up to 15 digits.

Number Methods
1. toString() : Returns a number as a string.
let x = 123;
[Link]();
(123).toString();
(100 + 23).toString()

2. toExponetial(): Returns a number written in exponential notation.


let x = 9.656;
[Link](2);
[Link](4);
[Link](6);
3. toFixed(): Returns a number written with a number of decimals.
let x = 9.656;
[Link](0);
[Link](2);
[Link](4);
[Link](6);
4. toPrecision(): Returns a number written with a specified length.
let x = 9.656;
[Link]();
[Link](2);
[Link](4);
[Link](6);
5. ValueOf(): Returns a number as a number.
let x = 123;
[Link]();
(123).valueOf();
(100 + 23).valueOf();
6. Number ():
a. Returns a number converted from its argument.
b. If the number cannot be converted, NaN (Not a Number) is returned.
c. Number () can also convert a date to a number.
Number(true);
Number(false);
Number("10");
Number(" 10");
Number("10 ");
Number(new Date("1970-01-01"))
7. parseFloat(): Parses its argument and returns a floating-point number.
parseFloat("10");
parseFloat("10.33");
parseFloat("10 20 30");
8. parseInt(): Parses its argument and returns a whole number.
parseInt("-10");
parseInt("-10.33");
parseInt("10");
9. EPSILON - The difference between 1 and the smallest JS number.
10. MAX_VALUE - The largest number possible in JavaScript
11. MIN_VALUE - The smallest number possible in JavaScript
12. MAX_SAFE_INTEGER - The maximum safe integer (253 - 1)
13. MIN_SAFE_INTEGER - The minimum safe integer -(253 - 1)
14. POSITIVE_INFINITY - Infinity (returned on overflow)
15. NEGATIVE_INFINITY - Negative infinity (returned on overflow)
16. NaN - A "Not-a-Number" value

Date Objects

1. new Date() creates a new date object with the current date and time:
new Date()
new Date(date string)
new Date(year, month)
new Date(year, month, day)
new Date(year, month, day, hours)
new Date(year, month, day, hours, minutes)
new Date(year, month, day, hours, minutes, seconds)
new Date(year, month, day, hours, minutes, seconds, ms)
new Date(milliseconds)

2. creates a date object with a specified date and time.


const d = new Date(2018, 11, 24, 10, 33, 30, 0);

3. JavaScript counts months from 0 to 11. January = 0. December = 11.


4. 6 numbers specify year, month, day, hour, minute, second:
const d = new Date(2018, 11, 24, 10, 33, 30);

5. 5 numbers specify year, month, day, hour, and minute:


const d = new Date(2018, 11, 24, 10, 33);
const d = new Date(2018, 11, 24, 10);

6. 3 numbers specify year, month, and day:


const d = new Date(2018, 11, 24)

7. You cannot omit month. If you supply only one parameter it will be treated as milliseconds.
const d = new Date(2018);

8. One , two digit years will be interpreted as 19xx


const d = new Date(99, 11, 24);

Displaying Dates:
1. toString() : convert date in string.
const d = new Date();
[Link]();
2. toDateString() : converts a date to a more readable format:
const d = new Date();
[Link]();
3. toUTCString(): method converts a date to a string using the UTC standard:
const d = new Date();
[Link]();

Date Input:
1. ISO Date "2015-03-25" (The International Standard)
2. Short Date "03/25/2015"
3. Long Date "Mar 25 2015" or "25 Mar 2015"

Parsing Dates :
Parse() method to convert it to milliseconds.
let msec = [Link]("March 21, 2012");

Get Date Methods:


1. getFullYear() - Get year as a four-digit number (yyyy)
2. getMonth() - Get month as a number (0-11)
3. getDate() - Get day as a number (1-31)
4. getDay() - Get weekday as a number (0-6).
const d = new Date();
var day = [Link]();
var daylist = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
[Link]( "Today is : " + daylist[day] );
5. getHours() - Get hour (0-23)
6. getMinutes() - Get minute (0-59)
7. getSeconds() - Get second (0-59)
8. getMilliseconds() - Get millisecond (0-999)
9. getTime() - Get time (milliseconds since January 1, 1970)

Set Date Methods


1. setDate() - Set the day as a number (1-31)
2. setFullYear() - Set the year (optionally month and day)
3. setHours() - Set the hour (0-23)
4. setMilliseconds() - Set the milliseconds (0-999)
5. setMinutes() - Set the minutes (0-59)
6. setMonth() - Set the month (0-11)
7. setSeconds() - Set the seconds (0-59)
8. setTime() - Set the time (milliseconds since January 1, 1970
Math Object
1. Math.E - returns Euler's number.
2. [Link] - returns PI.
3. Math.SQRT2 - returns the square root of 2.
4. Math.SQRT1_2 - returns the square root of ½.
5. Math.LN2 - returns the natural logarithm of 2.
6. Math.LN10 - returns the natural logarithm of 10.
7. Math.LOG2E - returns base 2 logarithm of E.
8. Math.LOG10E
9. [Link](x) - Returns x rounded to its nearest integer.
10. [Link](x) - Returns x rounded up to its nearest integer.
11. [Link](x) - Returns x rounded down to its nearest integer.
12. [Link](x)- Returns the integer part of x (new in ES6).
13. [Link]()
14. [Link]()

[Link]():
1. [Link]() returns a random number between 0 (inclusive), and 1 (exclusive):
2. [Link]() always returns a number lower than 1
3. [Link]() used with [Link]() can be used to return random integers.
[Link] ([Link] () * 10);
Random Function:
1. Returns a random number between min (included) and max (excluded):
Code:
function getRndInteger(min, max) {
return [Link]([Link]() * (max - min)) + min;
}
2. Returns a random number between min and max (both included):
Code:
function getRndInteger(min, max) {
return [Link]([Link]() * (max - min + 1)) + min;
}

Conditional statements
A. If statement:
 Use if to specify a block of code to be executed, if a specified condition is true.

if (condition) {
………………..
}
 Use else to specify a block of code to be executed, if the same condition is false.
if (condition) {
………………….
} else {
……………………
}

 Use else if to specify a new condition to test, if the first condition is false.
if (condition1) {
………………………….
} else if (condition2) {
…………………
} else {
…………………
}

B. Ternary Operator: JavaScript also contains a conditional operator that assigns a value to a
variable based on some condition.

Syntax : variablename = (condition) ? value1:value2

Code : let voteable = (age < 18) ? "Too young" : "Old enough" ;
C. for: if you want to run the same code repeatedly, each time with a different value.
code :
for (let i = 0; i < [Link]; i++) {
text += cars[i] + "<br>";
}
D. for( x in y ) loop:
code :
const numbers = [45, 4, 9, 16, 25];
let txt = "";
for (let x in numbers) {
txt += numbers[x];
}
*** Do not use for in over an Array if the index order is important.

E. for/of: JavaScript for of statement loops through the values of an iterate object.
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) {
text += x;
}
F. while:
G. do/while:
H. Switch statement:
The continue statement (with or without a label reference) can only be used to skip one loop
iteration. the break statement "jumps out" of a loop.

switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

Array

1. An array is a special variable, which can hold more than one value:
2. JavaScript, arrays use numbered indexes.
3. Last array index is [ [Link] - 1];
4. Arrays are a special type of objects.
5. Array indexes start with 0.
6. JavaScript does not support associative arrays.

Create array:
Method-1:
const array_name = [item1, item2, ...., ….];
Method-2:
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
Method-3:
Const car = new Array(“shuvo”,26); // no need to use new array method

Accessing Array Elements:


const cars = ["Saab", "Volvo", "BMW"];
let car = cars [0] ; // first element
[Link] (cars) // full array
let car = cars [ [Link] - 1]; // last index

Array is object:
1. Arrays are a special type of objects.

const person = {firstName:"John", lastName:"Doe", age:46};

Array method & property:


A. Length: The length property of an array returns the length of an array.
const p = [Link];

B. [Link](): to know the variable is array or object use [Link]() methods.


[Link](cars);

C. Instanceof (): The instanceof operator returns true if an object is created by a given constructor
cars instanceof Array;

D. toString() : method converts an array to a string of (comma separated) array values.


const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]([Link](“,”));

E. join() : method also joins all array elements into a string. But we can specify the separator;
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link](" * ");
F. pop() : removes the last element from an array.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]();

G. push() : adds a new element to an array at the end:


const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]("Kiwi");

H. shift (): removes the first array element and "shifts" all other elements to a lower index.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]();
I. unshift (): adds a new element to an array at the beginning , and "unshifts" older elements:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]("Lemon");

J. delete():
1. Array elements can be deleted using the JavaScript operator delete.
2. Using delete leaves undefined holes in the array.

const fruits = ["Banana", "Orange", "Apple", "Mango"];


delete fruits[0];

K. find():
1. find() method returns the value of the first element that passes a test.
2. find() method executes a function for each array element.
3. find() method returns undefined if no elements are found.
4. find() method does not execute the function for empty elements.
5. find() method does not change the original array.

Syntax:
[Link]( function(currentValue, index, arr), thisValue)

find((element) => { /* … */ })
find((element, index) => { /* … */ })
find((element, index, array) => { /* … */ })
Code:
var array = [10, 20, 30, 40, 50];
var found = [Link](function (element) {
return element > 20;
});

L. findIndex():
1. The findIndex() method executes a function for each array element.
2. The findIndex() method returns the index (position) of the first element that passes a
test.
3. The findIndex() method returns -1 if no match is found.
4. The findIndex() method does not execute the function for empty array elements.
5. The findIndex() method does not change the original array.

Syntax

[Link](function(currentValue, index, arr), thisValue)

M. includes () :
1. The includes() method returns true if an array contains a specified value.
2. The includes() method returns false if the value is not found.
3. The includes() method is case sensitive.

Syntax: [Link] (element, start);

const fruits = ["Banana", "Orange", "Apple", "Mango"];


[Link]("Banana", 3);

N. concat(): creates a new array by merging (concatenating) existing arrays. The concat() method
can also take strings as arguments.
const G = ["Cecilie", "Lone"];
const B = ["Emil", "Tobias", "Linus"];
const C = [Link](B);

const D = [Link](B, C); // three array concat

O. splice (added, removed, elements1, elements2):


1. adds new items to an array.
2. Splice() method work in original array.
3. The 1st defines the position where new elements should be added (spliced in).
4. The 2nd parameter defines how many elements should be removed.
5. The rest of the parameters ("Lemon”, "Kiwi") define the new elements to be added.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link](2, 0, "Lemon", "Kiwi");

P. slice(removed):
1. The slice() method slices out a piece of an array into a new array.
2. The slice() method creates a new array.
3. The slice() method does not remove any elements from the source array.
4. The method then selects elements from the start argument, and up to (but not
including) the end argument.

Q. sort ():

Syntax:
sort()
sort((a, b) => { /* … */ } )
sort( compareFn )
sort( function compareFn( a, b) { ..… })
Specifies a function that defines the sort order. If omitted, the array elements are converted to
strings, then sorted according to each character's Unicode code point value.

a = The first element for comparison.


b = The second element for comparison.

1. String Sort: this method sorts the array alphabetically.

Code:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]();
2. Numeric Sort:
 By default, the sort() function sorts values as strings.
 Because of this the sort() method will produce incorrect result when sorting numbers.
Code :
Ascending :
const points = [40, 100, 1, 5, 25, 10];
[Link](function(a, b){return a - b});
Descending:
const points = [40, 100, 1, 5, 25, 10];
[Link](function(a, b){return b - a});

3. Random Order:
const points = [40, 100, 1, 5, 25, 10];
[Link](function(){return 0.5 – [Link]()});

4. Sorting Object:
Code:
const cars = [
{ type:"Volvo", year:2016 },
{ type:"Saab", year:2001 },
{ type:"BMW", year:2010 }
];
[Link](function(a, b){return [Link] - [Link]});

R. reverse() : reverses the elements in an array.


S. [Link]: find the highest number in an array:
Code:
function myArrayMax(arr) {
return [Link](null, arr);
}
T. [Link]: find the lowest number in an array:
Code :
function myArrayMin(arr) {
return [Link](null, arr);
}

map():
a. The map() method creates a new array by performing a function on each array element.
b. The map() method does not execute the function for array elements without values.
c. The map() method does not change the original array.

const numbers1 = [45, 4, 9, 16, 25];


const numbers2 = [Link](myFunction);
function myFunction(value, index, array) {
return value * 2;
}

filter():
The [Link]() method is used to create a new array from a given array consisting of only those
elements from the given array which satisfy a condition set by the argument method.
const numbers = [45, 4, 9, 16, 25];
const over18 = [Link](myFunction);

function myFunction(value, index, array) {


return value > 18;
}
syntax:
[Link]( callback(element, index, arr ) , thisValue )

1. callback: This parameter holds the function to be called for each element of the array.
2. element: The parameter holds the value of the elements being processed currently.
3. index: is optional, it holds the index of the current Value element in the array starting
from 0.
4. arr: This parameter is optional; it holds the complete array on which Array.
5. thisValue: This parameter is optional, it holds the context to be passed as this to be used
while executing the callback function. If the context is passed, it will be used like this for
each invocation of the callback function, otherwise undefined is used as default.

the callback function does not use the index and array parameters, so they can be omitted:
const numbers = [45, 4, 9, 16, 25];
const over18 = [Link](myFunction);
function myFunction(value) {
return value > 18;
}

reduce()--- ES6

1. The reduce() method runs a function on each array element to produce (reduce it to) a
single value.
2. The reduce() method works from left-to-right in the array.
3. The reduce() method does not reduce the original array.

const numbers = [45, 4, 9, 16, 25];


let sum = [Link](myFunction, 100);
function myFunction(total, value) {
return total + value;
}

Syntax:
// Arrow function
reduce( (accumulator, currentValue) => { … } ,initvalue)
reduce( (accumulator, currentValue, currentIndex) => { … } )
reduce( (accumulator, currentValue, currentIndex, array) => { /* … */ } )
reduce( (accumulator, currentValue) => { /* … */ }, initialValue)
reduce( (accumulator, currentValue, currentIndex) => { /* … */ }, initialValue )
reduce((accumulator, currentValue, currentIndex, array) => { /* … */ }, initialValue)

// Callback function
reduce(callbackFn)
reduce(callbackFn, initialValue)
// Inline callback function
reduce(function (accumulator, currentValue) { /* … */ })
reduce(function (accumulator, currentValue, currentIndex) { /* … */ })
reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ })
reduce(function (accumulator, currentValue) { /* … */ }, initialValue)
reduce(function (accumulator, currentValue, currentIndex) { /* … */ }, initialValue)
reduce(function (accumulator, currentValue, currentIndex, array) { /* … */ }, initialValue)

Parameter:
1. function(accumulator, currentValue, index, arr) = It is the required parameter and is used to
run for each element of the array. It contains four parameters which are listed below:
a. accumulator: It is a required parameter and used to specify the initialValue or the
previously returned value of the function.
b. currentValue: It is a required parameter and is used to specify the value of the
current element.
c. currentIndex: It is an optional parameter and is used to specify the array index of
the current element.
d. array: It is an optional parameter and is used to specify the array object the current
element belongs to.
2. InitialValue = A value to which accumulator is initialized the first time the callback is called.

Maps ---- ES6


Map is a collection of elements where each element is stored as a Key, value pair. Map object can
hold both objects and primitive values as either key or value. When we iterate over the map object it
returns the key, value pair in the same order as inserted.

Create map
1. Instance of Object: we can create map object with new keyword.
Syntax: new Map()
code: const name = new Map();
2. With Constructor : If we want to initialize it directly from its constructor, we can pass an
array of “key-value” arrays:

Syntax: new Map([it]);

Code:
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200]
]);

Method of Maps :
A. set() method: Adding elements to a Map with the set() method:
const fruits = new Map ();
[Link]("apples", 500);
[Link]("bananas", 300);

B. get() Method: we can access Map elements using the get() method.
[Link]("apples");

C. size Property: You can get the number of elements in a Map using the size property.
[Link];
D. delete () Method: the delete() method to remove elements from a Map.
[Link]("apples");

E. has() Method : we can use the has() method to check if the element is in a Map
[Link]("apples");
F. forEach() Method: This method calls a function for each key/value pair in a Map:
let text = "";
[Link] (function(value, key) {
text += key + ' = ' + value;
})

G. entries() Method: this method returns an iterator object with the [key, values] in a Map:

let text = "";


for (const x of [Link]() ) {
text += x;
}

Sets

Destructuring ---- ES6


1. Destructuring is a JavaScript expression that allows us to extract data from arrays, objects and
set them into distinct variables.
2. It enables destructuring array or object elements into separate variables more quickly and
efficiently.
3. In destructuring, the left-hand side of the assignment operator contains variable(s) that will
store the destructured values. In contrast, the right-hand side has the array or object, which is
destructured.

Syntax :
const [a, b] = array;
const { a, b } = obj;

Destructing Arrays:
In JavaScript we access the array with index. We declared the array and then access the individual
value with help of index.
Code:
const person = [‘shuvo’, ‘karim’, ‘rahim’];
const x = person[0];
const y = person[1];
const z = person[2];
But in ES6 we can access the array with help of destructing assignment. we can use brackets [] for
array destructing. that the square brackets [ ] look like the array syntax but they are
not.

Syntax: const [ value1, value2 ] = arrayName.

Code:
const person = [‘shuvo’, ‘karim’, ‘rahim’];
const [x, y, z] = person;
[Link](x);
Swapping Variables:
We can swap the variable using destructuring assignment.
Code:
let x = 4;
let y = 7;
[x, y] = [y, x];
[Link](x); // 7
[Link](y); // 4
Skip Items:
The array elements can be skipped as well using a comma separator. We can skip unwanted items in
an array without assigning them to local variables.

const [ x, ,z] = ['one', 'two', 'three'];


[Link](x); // one
[Link](z); // three

Object Destructuring:
In JavaScript, we access the object property by dot(.) operator.

Code:
const user = {
name = “shuvo”;
}
const person= [Link];
But in ES6 we can access the object property with help of destructing assignment.

Syntax:

Code:
var employee = {
name: 'Jon',
id: 12345,
};
var {name, id} = employee;

Assign to New variable:


we can assign the property of object in new variable by colon ( : ).

Syntax: { propertyName : variableName } = objectName


Code:
const user = { name : “shuvo” , id : 123456 } ;
const { name : empName , id : empId} = user ;
[Link] (empName);
[Link](empId);

Error Handing:
If we return a null object in destructing, then JavaScript throw an error. To avoid this, you can use
the OR operator (||) to fallback the null object to an empty object:

let { firstName, lastName } = getPerson() || { } ;

Destructing for Object/ Array


Assign Default Values:
1. Array: We can set default value in array destructing. If variables are messing in array, then
default value is assigned in destructuring .

Code:
let arrValue = [10];
let [x = 5, y = 7] = arrValue;
[Link](x) ; // 10
[Link](y) ; // 7
2. Object: we can also set default value in object destructing.

Code:
const person = {
name: 'Jack',
}
const { name, age = 26} = person;
[Link](name); // Jack
[Link](age); // 26

Nested Destructuring :
1. Array: You can perform nested destructuring for array elements.

const arrValue = ['one', ['two', 'three']];


const [x, [y, z]] = arrValue;
[Link](x); // one
[Link](y); // two
[Link](z); // three
2. Object: we can also perform nested destructuring for object properties.
const person = {
name: 'Jack',
age: 26,
hobbies: {
read: true,
playGame: true
}
}
const { name , hobbies: { read, playGame } } = person;
[Link](name); // Jack
[Link](read); // true
[Link](playGame); // true
Rest Operator:
1. Array: You can assign some array elements to distinct variables and the other array elements
to a single variable with the help of the rest operator (...).

var [name , , ...city] = ["Monim", 28, "London",”Karachi”]


[Link](name); // "Monim"
[Link](city); // "London", "Karachi"

2. Object: we can use rest operator in object destructuring also.

const { a, ...others } = { a: 1, b: 2, c: 3 };
[Link](others); // { b: 2, c: 3 }

Spread Operator --------ES6

1. The spread operator is a tool that lets you spread out all the elements of an array or object
2. In JavaScript spread operator are added in ES6 version.
3. Spread operator are three dots (…) .
4. The spread operator (...) is used to expand or spread an iterable or an array.
5. It is mostly used in the variable array where there are more than 1 values are expected.
Syntax:
var variablename1 = [...value];

Use spread operator in array:


1. Copy Array:
let arr = ['a', 'b', 'c'];
let arr2 = [...arr];

2. Expand Array: You can also create a shallow copy of an array with the spread syntax.
const arr1 = ['one', 'two'];
const arr2 = [...arr1, 'three', 'four', 'five'];
3. Clone Array: In JavaScript, objects are assigned by reference and not by values. Here change
in one variable results in the change in both variables.
let arr1 = [ 1, 2, 3];
let arr2 = arr1;
[Link](arr2); // [1, 2, 3]
// append an item to the array
[Link](4);
[Link](arr1); // [1, 2, 3, 4]
[Link](arr2); // [1, 2, 3, 4]
if you want to copy arrays so that they do not refer to the same array, you can use the
spread operator. This way, the change in one array is not reflected in the other.
let arr1 = [ 1, 2, 3];
let arr2 = [...arr1];
[Link](arr2); // [1, 2, 3]
[Link](4);
[Link](arr1); // [1, 2, 3, 4]
[Link](arr2); // [1, 2, 3]
4. concatenate arrays:

let arr1 = [0, 1, 2];


const arr2 = [3, 4, 5];
arr1 = [...arr1, ...arr2];

Use spread operator in object :


1. Copy object :
const user1 = {
name: 'Jen',
age: 22
};
const copyUser = { ...user1 };

2. concatenate object:
const user1 = {
name: 'Jen',
age: 22,
};
const user2 = {
name: "Andrew",
location: "Philadelphia"
};
const concatUsers = {...user1, ...user2};
[Link](concatUsers)

Rest parameter ----- ES6


1. ES6 provides a new kind of parameter so-called rest parameter that has a prefix of three
dots (...)
2. Rest parameter is an improved way to handle function parameter, allowing us to handle various
input more easily as parameters in a function.
3. The rest parameter syntax allows a function to accept an indefinite number of arguments as an
array.
4. The rest parameters must be at the end.
Syntax: [a, b, ...args]
5. Assign the first and second items from numbers to variables and put the rest in an array.

Const numbers = [1, 2, 3, 4, 5, 6];


const [one, two, ...rest] = numbers;
code:
function myFun(a, b, ...manyMoreArgs) {
[Link]( a);
[Link](b);
[Link]( manyMoreArgs);
}
myFun ("one", "two", "three", "four", "five", "six");

Modules ------ES6
1. JavaScript modules rely on the import and export statements.
2. JavaScript modules allow you to break up your code into separate files.

A. Export:
You can export a function or variable from any file. You can create named exports two ways
1. In-line individually:
export const name = "Jesse";
export const age = 40;
2. All at once at the bottom:
const name = "Jesse"
const age = 40
export { name, age }
3. Default Exports
const message = () => {
const name = "Jesse";
const age = 40;
return name + ' is ' + age + 'years old.';
};
export default message;

B. Import:
You can import modules into a file in two ways, based on if they are named exports or default
exports.
1. Import from named exports
import { name, age } from "./[Link]";
2. Import from default exports
import message from "./[Link]";

Errors

A. try and catch:


1. The try statement allows you to define a block of code to be tested for errors while it is
being executed.
2. The catch statement allows you to define a block of code to be executed, if an error occurs
in the try block.
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}

B. throw Statement:
When an error occurs, JavaScript will normally stop and generate an error message. The throw
Statement allows you to create a custom error. The technical term for this is: JavaScript will throw
an exception (throw an error).
try {
If (x == "") {
throw "empty";
}
If (isNaN(x)) throw "not a number";
}
catch(err) {
[Link] = "Input is " + err;
}

C. finally, Statement:
The finally statement defines a code block to run regardless of the result.
try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
Block of code of the try / catch result
}

Scope
Scope determines the accessibility of variables, objects, and functions from different parts of the
code

Block scope:
1. Variables declared inside a { } block cannot be accessed from outside the block:
2. Variables declared with the var keyword can NOT have block scope.
{
let x = 2;
}
// x can NOT be used here
Function scope:
1. Variables declared within a JavaScript function, become LOCAL to the function.
2. Since local variables are only recognized inside their functions, variables with the same name
can be used in different functions.
3. Local variables are created when a function starts, and deleted when the function is
completed.
function myFunction() {
let carName = "Volvo";
}
Global scope:
1. A variable declared outside a function, becomes GLOBAL.
2. A global variable has Global Scope:
3. All scripts and functions on a web page can access it.
4. JavaScript, the global scope is the JavaScript environment.
5. In HTML, the global scope is the window object.
6. Global variables defined with the var keyword belong to the window object.
7. Global variables defined with the let keyword do not belong to the window object:
let carName = "Volvo";
function myFunction() {
// code here can also use carName
}
******
1. In "Strict Mode", undeclared variables are not automatically global.
2. Do NOT create global variables unless you intend to.

The Lifetime of JavaScript Variables


1. The lifetime of a JavaScript variable starts when it is declared.
2. Function (local) variables are deleted when the function is completed.
3. In a web browser, global variables are deleted when you close the browser window (or tab)

Hoisting
1. Hoisting is JavaScript's default behavior of moving declarations to the top.
2. a variable can be used before it has been declared.

x = 5; // Assign 5 to x
var x; // Declare x
LET:
1. Variables defined with let is hoisted to the top of the block, but not initialized as undefined.
2. Using a let variable before it is declared will result in a ReferenceError.
3. The variable is in a "temporal dead zone" from the start of the block until it is declared:

Const :
1. Using a const variable before it is declared, is a syntax errror, so the code will simply not run.

Initializations are Not Hoisted :


1. JavaScript only hoists declarations, not initializations.
var x = 5;
[Link](x + y)
var y = 7;
2. In this code all x and y variable are only hoists not initializations
var x;
var y;
x = 5;
[Link](x + y);
y=6
Use Strict – ES5
"use strict" Defines that JavaScript code should be executed in "strict mode". Strict mode is
declared by adding "use strict"; to the beginning of a script or a function.

1. Using a variable, without declaring it, is not allowed:


2. Using an object, without declaring it, is not allowed:
3. Deleting a variable (or object) is not allowed.
4. Deleting a function is not allowed.
5. Duplicating a parameter name is not allowed:
6. Octal numeric literals are not allowed:
7. Octal escape characters are not allowed:
8. Writing to a read-only property is not allowed:
9. Writing to a get-only property is not allowed:
10. Deleting an undeletable property is not allowed:
11. The word eval cannot be used as a variable:
12. The with statement is not allowed
13. “This” keyword in functions behaves differently in strict mode

This keyword:
1. In an object method, this refers to the object.
2. Alone, this refers to the global object.
3. In a function, this refers to the global object.
4. In a function, in strict mode, this is undefined.
5. In an event, this refers to the element that received the event.
6. Methods like call(), apply(), and bind() can refer this to any object

Object
A javaScript object is an entity having state and behavior (properties and method). JavaScript is an
object-based language. Everything is an object in JavaScript.

 Objects are variables too that allows you to store multiple collections of data.
 JavaScript is template based not class based. We do not need to create classes in order to create
objects.
 An object literal is a list of property key:values inside curly braces { }.

Syntax:
const object_name = {
key1: value1,
key2: value2
}
Code:

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

There are different ways to create new objects:


1. Using an Object Literal
2. Using the new Keyword
3. Using an Object Constructor
4. Using [Link]()
5. Using [Link]()
6. Using [Link]()

A. Using Object Literal : we can create an object using an object literal. An object literal uses { } to
create an object directly.

Syntax:
Object = {
property1:value1,
property2:value2
...............
}
Code :
const person = {
Age: 50,
eyeColor : "blue"
};
Code :
const person = {};
[Link] = 50;
[Link] = "blue";

B. Using Instance of Object : Create a single object, with the new keyword. the new keyword is
used with the Object() instance to create an object.

Syntax:
const objectName = new Object();
Code:
const person = new Object ();
[Link] = 50;
[Link] = "blue";

const person = new Object({


firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
});
C. Using Constructor Function : constructor function is used to create an object using
the new keyword. Here, you need to create function with arguments. Each argument value can
be assigned in the current object by using this keyword. The this keyword refers to the current
object.

Code :
function emp( id, name, salary){
[Link] = id;
[Link] = name;
[Link] = salary;
}
e=new emp(103,"Vimal Jaiswal",30000);

D. [Link](): Create an object using [Link]():


1. [Link]() method is used to create a new object with the specified prototype object
and properties.
2. [Link]() is used for implementing inheritance.
3. Here all child object inheritance parent method and prototype.

Syntax:
[Link](prototype , [properties-Object])

prototype : It is the prototype object from which a new object must be created.
Properties-Object : It is optional parameter. It specifies the enumerable properties to be
added to the newly created object.

const city = {
name: "dhaka",
age : 36
}
const mym = [Link](city); // no result
const mym = [Link](city, name)
***** Objects are mutable: They are addressed by reference, not by value.

[Link] vs new Object:


[Link]: In object create method, when we want inherit parents object, we need to create
object and return value.

let p = function Person (name, age) {


let person = [Link]([Link]);
[Link] = name;
return person;
}
[Link] = {
eat(){
[Link] ("eat ");
},
sleep(){
[Link]("sleep");
}
}
const sakib = p('sakib');
[Link]={ name: "shuvo" };
new Object: create an object with new keyword not need no assign in protype. prototype
create when object create.

let p = function Person(name, age){


[Link] = name;
}
[Link] = {
eat(){
[Link]("eat ");
},
sleep(){
[Link]("sleep");
}
}
const sakib = new p('sakib');
[Link]={ name: "shuvo" };

Object Properties:
A. Accessing property:
1. Using dot Notation:
Syntax: [Link]
Code:
const person = {
name: 'John',
age: 20,
};
[Link]([Link]); // John
2. Using bracket Notation:

Syntax : objectName["property"]
Code :
const person = {
name: 'John',
age: 20,
};
[Link](person["name"]); // John
B. Adding Property : we can add a property in an object by dot(.) notation.
Code:
const person = {
name: 'John',
age: 20,
};
[Link] = "English";
[Link]( person );
C. Deleting Property:
 The delete keyword deletes a property from an object.
 The delete keyword deletes both the value of the property and the property itself.
 After deletion, the property cannot be used before it is added back again.
 The delete operator is designed to be used on object properties. It has no effect on variables
or functions.
 The delete operator should not be used on predefined JavaScript object properties. It can
crash your application.

Code:
const person = {
name: 'John',
age: 20,
};
delete [Link];
delete person["age"];

D. Checking Property : To check if a property exists in an object, you use the in operator.
The in operator returns true if the propertyName exists in the objectName.

Syntax:
propertyName in objectName
Code:
let employee = {
name: 'Peter',
roll: 'Doe',

};
[Link]('roll' in employee);

Objects Methods
A. Accessing Method:
1. When we add a function as a value of property, we called it method of object. We can
access an object method using a dot notation by calling object method name. For invoked
method we use bracket ().

syntax:
[Link]()

code:
const person = {
firstName: "John",
id: 5566,
fullName: function() {
return [Link] ;
}
};

name = [Link]();

2. If you access the Object method name without (), it will return the function definition:
Code:
name = [Link];

B. Adding Method: We can add a method with dot(.) notation and pass function as value.
Code:
const person = {
firstName: "John",
id: 5566,
};
[Link] = function(){
[Link](“this is method add”);
}

Displaying Object Properties:


A. By name: The properties of an object can be displayed as a string.
const person = {
name: "John",
age: 30,
city: "New York"
};
[Link]("demo").innerHTML = [Link];

B. In a Loop:
Code:
const person = {
name: "John",
age: 30,
city: "New York"
};

for (let x in person) {


txt += person[x] + " ";
};
person.x will not work (Because x is a variable).

C. [Link](): Any JavaScript object can be converted to an array using this method.
Code:
const person = {
name: "John",
age: 30,
city: "New York"
};
const myArray = [Link](person);

D. [Link](): Any JavaScript object can be stringified (converted to a string) with the
JavaScript function.
const person = {
name: "John",
age: 30,
city: "New York"
};
let myString = [Link](person);

Object Constructors function:


Sometimes we need a "blueprint" for creating many objects of the same "type". The way to create
an "object type’ we use constructor function.

1. A constructor is a special function that creates and initializes an object instance of a class.
2. In JavaScript, a constructor gets called when an object is created using the new keyword.

Without parameter:
function User () {
[Link] = 'Bob';
}
var user = new User ();

With parameter:
function Person (first, last, age, eye) {
[Link] = first;
[Link] = last;
}
const ob1 = new Person ("John", "Doe");
const ob2 = new Person ("Sally", "Rally");
[Link];
[Link];

3. Each object created from the constructor function is unique.


4. You cannot add a property to an object constructor. But add in object.
5. You cannot add a new method to an object constructor the same way you add a new method to
an existing object.
Code:

function Person () {
[Link] = 'Sam'
}
let person1 = new Person();
let person2 = new Person();

[Link] = 20; // adding new property to person1


[Link]() = function (){
[Link](“dfkj”);
}

Constructor Function Vs Object Literal


1. Object Literal is generally used to create a single object. The constructor function is useful if
you want to create multiple objects
2. Each object created from the constructor function is unique. You can have the same
properties as the constructor function or add a new property to one object

Getter and Setter


there are two kinds of object properties---------------

Data properties : when access the property of object directly with dot(.)
Accessor properties: accessor properties are methods that get/set the value of an object with get
and set keyword.
1. get - to define a getter method to get the property value
2. set - to define a setter method to set the property value

JavaScript Getter:
1. getter() methods are used to access the properties of an object.
2. To create a getter method, the get keyword is used.

const student = {
firstName: 'Monica',
get getName() {
return [Link];
}
};
[Link]([Link]);
JavaScript Setter:
1. In JavaScript, setter methods are used to change the values of an object.
2. To create a setter method, the set keyword is used.

const student = {
firstName: 'Monica',
set changeName(newName) {
[Link] = newName;
}
};
[Link]([Link]);
[Link] = 'Sarah';
[Link]([Link]);

[Link](): [Link]() method to add getters and setters.


const student = {
firstName: 'Monica'
}
[Link](student, "getName", {
get : function () {
return [Link];
}
});
[Link](student, "changeName", {
set : function (value) {
[Link] = value;
}
});
[Link]([Link]); // Monica
[Link] = 'Sarah';
[Link]([Link]); // Sarah

Object Prototypes
1. JavaScript is a prototype-based language.
2. Whenever we create a function using JavaScript, JavaScript engine adds a prototype property
inside a function.
3. Prototype property is basically an object (also known as Prototype object).
4. We can attach methods and properties in a prototype object
5. Which enables all the other objects to inherit these methods and properties.
6. All JavaScript objects inherit properties and methods from a prototype.

<script>
function Person(name, job){
[Link] = name;
[Link] = job;
}
const shuvo = new Person(“shuvo” , ”job”)
</script>

Property add: The JavaScript prototype property allows you to add new properties to object
constructors:
function Person(first, last) {
[Link] = first;
[Link] = last;
}
[Link] = "English";

Method add: The JavaScript prototype property also allows you to add new methods to objects
constructors:
function Person(first, last) {
[Link] = first;
[Link] = last;
}
[Link] = function() {
return [Link] + " " + [Link];
};
Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.

Function

1. JavaScript functions are defined with the function keyword.


2. You can use a function declaration or a function expression.
Syntax:
function <functionName> (parameters) {
…………………….
}
Declared functions are not executed immediately. They are "saved for later use", and will be
executed later, when they are invoked with “() “.

function myFunction(a, b) {
return a * b;
}
myFunction();

Function as Variable:
1. Function can be store in variable.
2. After a function expression has been stored in a variable, the variable can be used as a function.
3. Functions stored in variables do not need function names. They are always invoked (called) using
the variable name.
4. The function above ends with a semicolon because it is a part of an executable statement.

const x = function (a, b) { return a * b };


let z = x(4, 3);

JavaScript Function Constructor (Function ())


1. The function statement is not the only way to define a new function; you can define your
function dynamically using Function() constructor along with the new operator.
2. Function() constructor creates a new Function object.
3. Calling the constructor directly can create functions dynamically.
4. Function() can be called with or without new. Both create a new Function instance.

Syntax:
new Function( functionBody)
new Function(arg0, functionBody)
new Function(arg0, arg1, functionBody)

Function(functionBody)
Function(arg0, functionBody)
Function(arg0, arg1, functionBody)
Code :
const adder = new Function('a', 'b', 'return a + b');

Self-Invoking Functions
1. A self-invoking expression is invoked (started) automatically, without being called.
2. Function expressions will execute automatically if the expression is followed by ().
3. Function not necessary any name.

( Function () {
let x = "Hello!!”; // I will invoke myself
}) ();

Function Parameters
Parameter: When a value is passed when declaring a function, it is called parameter.
Argument: when the function is called, the value passed is called argument.

1. JavaScript function definitions do not specify data types for parameters.


2. JavaScript functions do not perform type checking on the passed arguments.
3. JavaScript functions do not check the number of arguments received.

function functionName(para1, para2, ….. ) {


……………….
}
4. If a function is called with missing arguments (less than declared), the missing values are set
to undefined.
function sum(x , y) {
return x*y; // y = undefined
}
sum(12);

5. We can assign a default value to parameter.


function sum (x, y = 2) {
return x*y;
}
Sum(12);
The Arguments
1. JavaScript functions have a built-in object called the arguments object.
2. Arguments are the real values passed to (and received by) the function.
3. arguments name array receives all the argument passed in function.

x = findMax(1, 123, 500, 115, 44, 88); // argument value……


function findMax() {
let max = -Infinity;
for (let i = 0; i < [Link]; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
1. JavaScript arguments are passed by value: The function only gets to know the values, not the
argument's locations.
2. If a function changes an argument's value, it does not change the parameter's original value.
3. Changes to arguments are not visible (reflected) outside the function.

Anonymous functions
1. An anonymous function is a function without a name.
2. Anonymous function should write inside () bracket, if it is not assigning the variable.
Method- 1 :
function() {
// Function Body
}
Method-2 :
( function () {
………………………
});

3. if you want to create a function and execute it immediately after the declaration, you can
declare an anonymous function like this:

( function() {
[Link]('IIFE');
} )();
4. the anonymous function has no name between the function keyword and parentheses ().

Syntax:
let show = function() {
[Link]('Anonymous function');
};
show();

Arrow Functions ES-6

1. Arrow functions allows a short syntax for writing function expressions.


2. You don't need the function keyword, the return keyword, and the curly brackets.
3. Arrow functions are not hoisted. They must be defined before they are used.
Syntax:
// ES5
var x = function(x, y) {
return x * y;
}

// ES6
const x = (x, y) => x * y;
const x = (x, y) => { return x * y };

Advanced syntax:
1. To return an object literal expression requires parentheses around expression:
(params) => ( { foo: "a" } )
2. Rest parameters are supported, and always require parentheses:
(a, b, ...r) => expression
3. Default parameters are supported, and always require parentheses:
(a=400, b=20, c) => expression

4. Destructuring within params is supported, and always requires parentheses:


([a, b] = [10, 20]) => a + b ; // result is 30
({ a, b } = { a: 10, b: 20 }) => a + b; // result is 30

Avoid Arrow Function:


1. Do not use arrow functions to create methods inside objects.

Code:

const obj = {
name : “shuvo”,
show : () => [Link]([Link]);
entry(value) {
[Link]=value;
},
}
[Link]();
[Link](“shuvo”);

2. Cannot use an arrow function as a constructor.

let Foo = () => { };


let foo = new Foo();
3. Arrow functions aren't suitable for call, apply and bind methods,

Function Methods

1. call (),
2. apply (),
3. bind ()
call() method :
1. In JavaScript all functions are object.
2. The call() method takes arguments separately.
3. With the call() method, you can write a method that can be used on different objects.
Code–1:
const person = {
fullName: function() {
return [Link] + " " + [Link];
}
}
const person1 = {
firstName:"John",
lastName: "Doe"
}
[Link](person1);
Code-2:
const person = {
fullName: function(city, country) {
return [Link] + " " + [Link] + "," + city ;
}
}
const person1 = {
firstName : "John",
lastName : "Doe"
}
[Link](person1, "Oslo");

apply() Method:
1. The apply() method is like the call()
2. With the apply() method, you can write a method that can be used on different objects.
3. The apply() method takes arguments as an array.
Code :
const person = {
fullName: function(city, country) {
return [Link]+"," + city + "," + country;
}
}
const person1 = {
firstName:"John",
}
[Link](person1, ["Oslo", "Norway"]); // array in apply()

bind() method :
With the bind() method, an object can borrow a method from another object.
const person = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return [Link] + " " + [Link];
}
}
const member = {
firstName : "Hege",
lastName : "Nilsen",
}
let fullName = [Link](member);

Closures:
A) Nested Function: a function can also contain another function. This is called a nested
function.
Code:
function greet(name) {
function displayName() {
[Link]('Hi' + ' ' + name);
}
displayName();
}
greet('John'); // Hi John

B) Returning a Function: In JavaScript, you can also return a function within a function.
Code:
function greet(name) {
function displayName() {
[Link]('Hi' + ' ' + name);
}
return displayName;
}
const g1 = greet('John');

C) Closure:
 A closure is created when a function is defined inside another function and the inner
function remembers variables from the outer function’s scope — even after the outer
function has finished executing.
 Closures help us keep variables private (not directly accessible from outside).
 They’re often used for data privacy and encapsulation in JavaScript.
Code:

function greet() {
let name = 'John';
function displayName() {
return 'Hi' + ' ' + name;
}
return displayName;
}
const g1 = greet();
[Link](g1);
[Link](g1());

Asynchronous
1. JavaScript functions are executed in the sequence they are called.
2. Not in the sequence they are defined.
function myFirst() {
myDisplayer("Hello");
}
function mySecond() {
myDisplayer("Goodbye");
}
myFirst();
mySecond();
mySecond();
myFirst();
Sometimes you would like to have better control over when to execute a function.
Suppose you want to do a calculation, and then display the result.
Example:
function myDisplayer(some) {
[Link]("demo").innerHTML = some;
}
function myCalculator(num1, num2) {
let sum = num1 + num2;
return sum;
}
let result = myCalculator(5, 5);
myDisplayer(result);
The problem of example above, is that you have to call two functions to display the result.

Other Way:
function myDisplayer(some) {
[Link]("demo").innerHTML = some;
}
function myCalculator(num1, num2) {
let sum = num1 + num2;
myDisplayer(sum);
}
myCalculator(5, 5);
The problem of example, is that you cannot prevent the calculator function from displaying the
result.

How JavaScript Asynchronous Works:


when JavaScript code run in browser, all code converts into machine language. Then browser
interpret all the code. Browser have two things.

1. runtime
2. engine
A. Runtime:
Runtime is the environment in which a programming language executes. JavaScript’s runtime
majorly constitutes three things namely JavaScript Engine, Web API, Call stack. JavaScript can work
with asynchronous code as well as synchronous code.

The unique feature of JavaScript’s runtime is that even though JavaScript’s interpreter is single-
threaded, it can execute multiple codes at a time using concurrent fashion in a non-blocking way.
This enables asynchronous behavior. As the interpreter is not multithreaded, it rules out parallelism.

B. JavaScript Engine:
JavaScript engine can be considered as the heart of the runtime. It is the place where each code is
executed. JavaScript engine constitutes of Heap storage and call stack. Let’s understand each of
those. JavaScript is a single-threaded language. This means it has only one call stack and one
memory heap. Hence, it can only execute one code at a time. In other words, the code is executed in
an orderly fashion. It must execute one code in the call stack before moving to the next code to be
executed. There are two types of code tasks in JavaScript, asynchronous code which runs and gets
executed after certain loading, synchronous, which gets executed instantaneously.

1. Heap : It is the place where all the objects and data are stored. This is similar to the heap storage
we see on various other languages like C++, Java, etc. It contains the store of the data related to
all the objects, arrays, etc. that we create in the code.
2. Call Stack: It is the place where the code is stacked before the execution. It has the properties of
a basic stack (first in last out). Once a coding task is stacked into the call stack, it will be
executed. There is an event loop that takes place and this is the one that makes the JavaScript
interpreter smart. It is responsible for concurrent behavior.
3. Web API: JavaScript has the access to different web API’s and it adds a lot of functionality. For
example, JavaScript has the access to the DOM API, which gives access to the DOM tree to
JavaScript. Using this, we can make changes to the HTML elements present on the browser. Also,
you can think of the timer, which gives it access to the time-related functions, etc. Also, the
geolocation API which gives it access to the location of the browser. Like this, JavaScript has the
access to various other APIs.
4. Callback Queue: This is the place where asynchronous code is queued before passing to the call
stack. The passing of the code task from the callback queue to the call stack is taken care of by
the event loop. In addition to this, there is also a micro tasks queue.

JavaScript Callbacks
A function passed as an argument to another function is called callbacks. Callbacks are just the name
of a convention.

When doing a complex task, we break that task down into smaller steps. To help us establish a
relationship between these steps according to time (optional) and order, we use callbacks.
function myDisplayer(some) {
[Link]("demo").innerHTML = some;
}
function myCalculator (num1, num2, myCallback) {
let sum = num1 + num2;
myCallback(sum);
}
myCalculator (5, 5, myDisplayer);

**** When you pass a function as an argument, remember not to use parenthesis.
Right: myCalculator(5, 5, myDisplayer);
Wrong : myCalculator(5,5, MyDisplayer);
Callback Hell:
When multiple nested callback is called, callback hell occurred.
const makeBurger = () => {
getBeef(function(beef) {
cookBeef(beef, function(cookedBeef) {
getBuns(function(buns) {
putBeefBetweenBuns(buns, beef, function(burger) {
// Serve the burger
});
});
});
});
};

Asynchronous
1. Functions running in parallel with other functions are called asynchronous
2. In the real world, callbacks are most often used with asynchronous functions.

Asynchronous function:

1. setTImeout()
2. setInterval()

setTimeout() : with method we called the function after specific time.


setTimeout( myFunction, 3000);
function myFunction () {
[Link]("demo").innerHTML = "I love You !!";
}
setInterval() :
1. method continues calling the function after specific time.
2. To remove clearInterval() is called, or the window is closed.
[Link]( “dlkj” )
setInterval(myFunction, 1000);
function myFunction() {
[Link](“function”);
}
[Link](“finish”)

Promises
You write a function A() that fetch all the data from other website. After fetch data you show all the
data in a table. If data not fetch then table not show.
Here we learn two terms –
producing code: That do something and takes time. Here A() is producing code.
consuming code: That wants the result of the “producing code” once it’s ready. Here when data
fetch is complete table will show.

1. promise is a special JavaScript object that links the “producing code” and the “consuming code”
together.
2. Promises is an object which is invented to solve the problem of callback hell and to better handle
our tasks.
3. You must use a Promise method to handle promises.

Syntax Promise:
let promise = new Promise (function (resolve, reject) {
// executor (the producing code, "A ()")
});

1. The function passed to new Promise is called the executor. When new Promise is created, the
executor runs automatically. It contains the producing code which should eventually produce
the result
2. Its arguments resolve and reject are callbacks provided by JavaScript itself. Our code is only
inside the executor.
3. When the executor obtains the result, be it soon or late, doesn’t matter, it should call one of
these callbacks:
a. resolve(value) — if the job is finished successfully, with result value.
b. reject(error) — if an error has occurred, error is the error object.

Promises object has two properties:


a. state
b. result

State value Means Result


Pending initial state, neither fulfilled Undefined
nor rejected
Fulfilled meaning that the operation Result value
was completed successfully.
Rejected meaning that the operation Error value
failed.
Example:
let promise = new Promise (function (resolve, reject) {
setTimeout (() => resolve("done"), 1000);
});
We can see two things by running the code above:

1. The executor is called automatically and immediately (by new Promise).


2. The executor receives two arguments: resolve and reject. These functions are pre-defined
by the JavaScript engine, so we don’t need to create them. We should only call one of them
when ready.

Resolve called:
let promise = new Promise(function(resolve, reject) {
setTimeout(() => resolve("done"), 1000);
});

After one second of “processing”, the executor calls resolve("done") to produce the result. This
changes the state of the promise object:

That was an example of a successful job completion, a “fulfilled promise”.

Reject called:
let promise = new Promise(function(resolve, reject) {
setTimeout(() => reject(new Error("Whoops!")), 1000);
});
The call to reject(...) moves the promise object to "rejected" state:

Promise Consumers:

A Promise object serves as a link between the executor (the “producing code”) and the consuming
functions, which will receive the result or error.

Consuming functions can be registered using the methods-


1) .then
2) .catch
then ():
then() is invoked when a promise is either resolved or rejected. It may also be defined as a career
which takes data from promise and further executes it successfully.

Then () syntax: .then ( peram_1 , peram_2 );

then() method takes two functions as parameters.

1. Param_1: It is a function. First function is executed if promise is resolved and a result is received.
2. Parram_2: It is also a Function. Second function is executed if promise is rejected.

If we’re interested only in successful completions, then we can provide only one function argument
to .then:

let promise = new Promise(resolve => {


setTimeout(() => resolve("done!"), 1000);
});
[Link](alert);

catch() :

catch() is invoked when a promise is either rejected or some error has occurred in execution. It is
used as an Error Handler whenever at any step there is a chance of getting an error

.catch( param_1 )
Param_1: it is a function. Function to handle errors or promise rejections.

let promise = new Promise((resolve, reject) => {


setTimeout(() => reject(new Error("Whoops!")), 1000);
});
[Link](alert);

We can use then() as like catch.


.then( null, param_2);
Here param_2 take error as like catch().

Finally() :

1. The .finally() handler performs cleanups like stopping a loader, closing a live connection, and so
on.
2. The finally() method will be called irrespective of whether a promise resolves or rejects.
3. It passes through the result or error to the next handler which can call a .then() or .catch() again.
4. A finally handler has no arguments. In finally we don’t know whether the promise is successful or
not.
5. A finally handler also shouldn’t return anything. If it does, the returned value is silently ignored.

let loading = true;


loading && [Link]('Loading...');

promise = getPromise(ALL_POKEMONS_URL);

[Link](() => {
loading = false;
[Link](`Promise Settled and loading is ${loading}`);
}).then((result) => {
[Link]({result});
}).catch((error) => {
[Link](error)
});

Promise Chain

The [Link]() call always returns a promise. This promise will have the state as pending and
result as undefined. It allows us to call the next .then method on the new promise.

let promise = getPromise(ALL_POKEMONS_URL);


[Link](result => {
let > return onePokemon;
}).then( {
[Link](onePokemonURL);
return getPromise(onePokemonURL);
}).then(pokemon => {
[Link]([Link](pokemon));
}).catch(error => {
[Link]('In the catch', error);
});

How to Handle Multiple Promises

1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]
6. [Link]

JavaScript Async
1. "async and await make promises easier to write"
2. async makes a function return a Promise
3. await makes a function wait for a Promise

Async Syntax:
async function myFunction() {
return "Hello";
}
myFunction().then(
function(value) {myDisplayer(value);},
function(error) {myDisplayer(error);}
);
Await Syntax:
1. The await keyword can only be used inside an async function.
2. The await keyword makes the function pause the execution and wait for a resolved promise
before it continues:

JSON

1. JSON is a format for storing and transporting data.


2. JSON is often used when data is sent from a server to a web page.
3. JSON stands for JavaScript Object Notation
4. JSON is a lightweight data interchange format
5. JSON is language independent *
6. JSON is "self-describing" and easy to understand

JSON Example:

{
"employees": [
{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Anna", "lastName":"Smith" },
{ "firstName":"Peter", "lastName":"Jones" }
]
}
JSON Syntax Rules:

1. Data is in name/value pairs


2. Data is separated by commas
3. Curly braces hold objects
4. Square brackets hold arrays

JSON strings into JavaScript objects:

Use the JavaScript built-in function [Link]() to convert the string into a JavaScript object:

let text = '{ "employees" : [' +


'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" }
]
}';
const obj = [Link](text);

Converting An Object into a JSON string:

Use the JavaScript built-in function [Link]() to convert object into a JSON string
Class
1. Use the keyword class to create a class.
2. Always add a method named constructor():
3. Then add any number of methods.

Syntax:
class ClassName {
constructor() { ... }
method_1() { ... }
method_2() { ... }
}
Code:
class Car {
constructor(name, year) {
[Link] = name;
[Link] = year;
}
age() {
let date = new Date();
return [Link]() - [Link];
}
}
let myCar1 = new Car("Ford", 2014);
let myCar2 = new Car("Audi", 2019);

Class Inheritance:
To create a class inheritance, use the extends keyword.

class Car {
constructor(brand) {
[Link] = brand;
}
present() {
return 'I have a ' + [Link];
}
}
class Model extends Car {
constructor(brand, mod) {
super(brand);
[Link] = mod;
}
show() {
return [Link]() + ', it is a ' + [Link];
}
}

The super () method refers to the parent class.


By calling the super() method in the constructor method, we call the parent's constructor method
and gets access to the parent's properties and methods.

Getters and Setters:


It can be smart to use getters and setters for your properties, especially if you want to do something
special with the value before returning them, or before you set them.

To add getters and setters in the class, use the get and set keywords.
class Car {
constructor(brand) {
[Link] = brand;
}
get cnam() {
return [Link];
}
set cnam(x) {
[Link] = x;
}
}

even if the getter is a method, you do not use parentheses when you want to get the property value.

Web API
1. It can extend the functionality of the browser
2. It can greatly simplify complex functions
3. It can provide easy syntax to complex code

Geolocation API
The Geolocation API allows the web application to access your location if you agree to share it.

The Geolocation API is available through the [Link] object.

Method:

1. [Link]():

getCurrentPosition(function )
getCurrentPosition(success, error)
getCurrentPosition(success, error, options)

code:
[Link]( show , onError);
function show( e ){
[Link](e)
}
2. [Link]()
3. [Link]()

Form validate API


Method:
1. setCustomValidity(): Sets the validation Message property of an input Element.
2. checkValidity(): Returns true if an input element contains valid data.

Example:
<input id="id1" type="number" >
<button > <p id="demo"></p>
<script>
function myFunction() {
const m = [Link]("id1");
if (! [Link]() ) {
[Link]("demo").innerHTML = [Link];
}
}
</script>

Validation DOM Properties:

1. validity : Contains boolean properties related to the validity of an input element.


2. validationMessage : Contains the message a browser will display when the validity is false.
3. willValidate: Indicates if an input element will be validated.

Validity Properties:

1. customError: Set to true, if a custom validity message is set.


2. patternMismatch: Set to true, if an element's value does not match its pattern attribute.
3. rangeOverflow: Set to true, if an element's value is greater than its max attribute.
4. rangeUnderflow: Set to true, if an element's value is less than its min attribute.
5. stepMismatch: Set to true, if an element's value is invalid per its step attribute.
6. tooLong : Set to true, if an element's value exceeds its maxLength attribute.
7. typeMismatch: Set to true, if an element's value is invalid per its type attribute.
8. valueMissing: Set to true, if an element (with a required attribute) has no value.
9. Valid: Set to true, if an element's value is valid.

Example-1:
<input id="id1" type="number" max="100">
<button > <p id="demo"></p>
<script>
function myFunction() {
let text = "Value OK";
if ([Link]("id1").[Link]) {
text = "Value too large";
}
}
</script>

History API
The Web History API provides easy methods to access the [Link] object.
Code:
<button Back</button>
<script>
function myFunction() {
[Link]();
}
</script>
Method && Properties:
1. length: Returns the number of URLs in the history list
2. back(): Loads the previous URL in the history list
3. forward(): Loads the next URL in the history list
4. go(): Loads a specific URL from the history list

Storage API
The Web Storage API is a simple syntax for storing and retrieving data in the browser. There are two
types of storage:
A) localStorage Object:
1. The localStorage object provides access to a local storage for a particular Web Site. It allows
you to store, read, add, modify, and delete data items for that domain.
2. The data is stored with no expiration date, and will not be deleted when the browser is
closed.
3. The data will be available for days, weeks, and years.

code:
[Link]("name", "John Doe");
[Link]("name");

B) sessionStorage Object:
1. The sessionStorage object is identical to the localStorage object.
2. The difference is that the sessionStorage object stores data for one session.
3. The data is deleted when the browser is closed.
Code:
[Link]("name", "John Doe");
[Link]("name");
Method and Property:
1. key(n): Returns the name of the nth key in the storage
2. length: Returns the number of data items stored in the Storage object
3. getItem(keyname): Returns the value of the specified key name
4. setItem(keyname, value): Adds a key to the storage, or updates a key value (if it already
exists)
5. removeItem(keyname): Removes that key from the storage
6. clear (): Empty all key out of the storage
C) cookie:
An HTTP cookie is a piece of data that a server sends to a web browser. Then, the web browser
stores the HTTP cookie on the user’s computer and sends it back to the same server in the later
requests.

1. Set cooke: [Link] = "username=admin";


2. Get cookie: const str = [Link];
3. Remove cookie: [Link]('username');

Workers API
A web worker is a JavaScript running in the background, without affecting the performance of the
page.

Worker: Web Workers are a simple means for web content to run scripts in background threads.
The worker thread can perform tasks without interfering with the user interface.

1. Check worker:
if (typeof(Worker) !== "undefined") {

} else {

2. Create worker:
w = new Worker("demo_workers.js");

3. Method:
a) postMessage(message : Object, [transfer : Array]) :
b) onmessage:
[Link] = ()=>{
}
c) onerror:
[Link]=()=>{
}
d) terminate() :
[Link]();

Fetch: The fetch () method in JavaScript is used to request data from a server. The request can be of
any type of API that return the data in JSON or XML.

Syntax:
fetch (param_1, param_2)
. then ( response => [Link]() )
. then ( data => [Link](data) );
Param_1: the URL to access.
Param_2: It is an array of properties. It is an optional parameter.
Code:
const data = { username: 'example' };
let options = {
method: 'POST',
headers: {
'Content-Type': 'application/json ;
charset=utf-8'
},
body: [Link](data)
}
let req = fetch ( "[Link] , options );
[Link](res => res. json () )
. then ( d => { [Link](d) })

Async Await: With Async Await method with fetch() method to make promises in a more concise
way. Async functions are supported in all modern browsers.

Syntax:
async function funcName(url){
const response = await fetch(url);
var data = await [Link]();
}

BOM

Window Location
1. The [Link] object can be used to get the current page address (URL)
2. We can redirect the browser to a new page.
3. The [Link] object can be written without the window prefix.
Property :
a. [Link] - returns the href (URL) of the current page
b. [Link] - returns the domain name of the web host
c. [Link] - returns the path and filename of the current page
d. [Link] - returns the web protocol used (http: or https:)
e. [Link]() - loads a new document
code :
[Link]("demo").innerHTML = [Link];
[Link]("demo").innerHTML = [Link];

DOM – 65 (yahoo)

DOM targeting method


A. getElementById:
var m = Document. getElementById (“main”);
B. getElementByTagName:
var m = Document. getElementByTagName(“div”);
C. getElementByclass: it target all tag with same class name.
D. querySelector:
1. we can target the value with help CSS selector.
2. It targets only first node.
Id(#) selector : [Link](“#main”).innerHTML;
Class(.) selector : [Link](“.main”).innerHTML;
E. querySelectorAll:
1. we can target the value with help CSS selector.
2. It target all node.
3. It return a array
Id(#) selector : [Link](“#main”).innerHTML;
Class(.) selector: [Link](“.main”).innerHTML;

GET :
1. innerText: it return all text only inside the tag.
Code :
<div>
<p>The text content of the button element is </p>
<p id="demo"> </p>
<p>The innerText property and earlier.</p>
</div>
var x = [Link](“main”).innerText;
Output:
The text content of the button element is.
The innerText property and earlier

2. innerHTML: it return all text and tag inside the tag.


Code:
<div>
<p>The text content of the button element is:</p>
<p id="demo"> </p>
<p>The innerText property and earlier.</p>
</div>
var x = [Link](“main”).innerHTML;
Output:
<div>
<p>The text content of the button element is:</p>
<p id="demo"> </p>
<p>The innerText property and earlier.</p>
</div>

3. getAttribute: with this we can get attribute value of tag.


code:
<div id=”head” class=”container”>
var x = [Link](“head”).getAttribute(“class”);
output: container.

4. Attribute: it return all attribute of a tag in array.


code:
<div id=”head” class=”container” style=” color: red”>
var x = [Link](“head”).Attribute[1];
var x = [Link](“head”).Attribute[2];
output:
class=”container “
style=”color:red”

Attribute also have properties –


name: with name properties we can find name of attribute.
var x = [Link](“head”).Attribute[2].name ;
output: style
value : it return value of attribute .
var x = [Link](“head”).Attribute[2].value ;
output: color : red

SET
1. innerText: we can change text inside tag.
[Link](“main”).innerText=”hello world”;

2. innerHTML: we can change tag inside the tag.


[Link](“main”).innerHTML=”<h1> doremon </h1>

3. setAttribute: we can set attribute and value .


[Link](“head”).setAttribute(“class”,”syz”);

CSS style
style :
1. with this we can get element style.
2. We can change CSS of element.
3. To set value for CSS property we use camel case.

<p id=”main” style=” border:1px solid red; color:black; ”> hello world </p>
[Link](“#main”).[Link]=”blue”;
className:
1. We can get class attribute value of an element.
2. we can set class in an element .
3. it return string.
<p style=” border:1px solid red; color: black; ”> hello world </p>
[Link](“#main”).className =”blue”;
classList:
1. We can get class attribute value of an element.
2. we can set class in an element .
3. it return array of class.
<p style=” border:1px solid red; color: black; ”> hello world </p>
[Link](“#main”).classList =”blue”
method of classList:
a. add(): we add class in element by it.
<p style=” border:1px solid red; color: black; ”> hello world </p>
[Link](“#main”).[Link](“xyz”) ;
b. remove(): we can remove class attribute .

<p style=” border:1px solid red; color: black; ”> hello world </p>
[Link](“#main”).[Link](“xyz”) ;
c. Length: we can count how many class in element.
d. toggle : we toggle class attribute by this method.

EVENT --66
1. Click (onclick)
2. Double click ( ondbclick)
3. Right click (onContextMenu)
4. Mouse hover (onmouseenter)
5. Mouse Out (onmouseout)
6. Mouse Down (onmousedown)
7. Mouse up (onmouseup)
8. Key press (onkeypress)
9. Key Up (onkeyup)
10. Load (onload)
11. Unload (onunload)
12. Resize (onresize)
13. Scroll (onscroll)

addEventListener:
1. With this we can add an event handler to an element.
2. Here in event on not add

Syntax: [Link](event, function, useCapture);


Parameter:
event: The name of the event.
function: The function to run when the event occurs.
useCapture :
1. Optional (default = false).
2. false – it called inner div first .
3. true - it called outer div first.
Code :
<button id=”main”> click me </button>
var main = [Link](“main”);
[Link](“click”, function(){
[Link](“hello world”);
})

removeEventListener : we can remove an event from an element with this.


<button id=”main” click me </button>
var main = [Link](“main”);
[Link](“click”, function(){
[Link](“main”).removeEventListener(“click”,”abc”)
})

Traversal Method
1. parentNode
2. parentElement
3. Children
4. childNOdes
5. firstChild
6. firstElementChild
7. lastChild
8. lastElementChild
9. nextElementSibling
10. nextSibling
11. previousElementSibling
12. previousSibling

You might also like