JavaScript Tutor Joes
JavaScript Tutor Joes
JavaScript Tutor Joes
1
• Function in JavaScript
• Block Scope and Function Scope
• Rest Parameter vs Spread
• Parameter Destructuring in JavaScript
• Callback Functions in JavaScript
• Closure Functions
• forEach in JavaScript
• Filter Practical Samples
• Map Practical Samples
• Reduce Practical Samples
• Optional Chaining in JavaScript
• Function Inside Object
• Call Apply and Bind in JavaScript
• Arrow Function vs this Keyword
• Creating Objects in JavaScript
• Prototype and Prototypal Inheritance in JavaScript
• Class and Inheritance in JavaScript
• Getter and Setter in JavaScript
• Static Methods and Properties
• Sets in Javascript
• Exploring Map in JavaScript
• Destructuring Assignment
• Document Object Model
• DOM Family Structure
• DOM Family Tree Method
• DOM Traversing Method
• DOM Create Method
• DOM Output Possibilities
• DOM ClassList and Attributes
• DOM Mouse Events
• DOM Keyboard Events
• DOM Form Events
• DOM Touch Events
• Example of Touch Events
• Promise in Javascript
• Async and await in Javascript
• Fetch api in Javascript
• Event Loop in Javascript
• Event Bubbling in Javascript
• Event Delegation in Javascript
• Debounce function in Javascript
• Array Local Storage in Javascript
• Object Local Storage in Javascript
• Template Theme Change in Javascript
• Session Storage in Javascript
2
Javascript Tutorial
Why Javascript..?
3
Getting Started with JavaScript Programming: A
Beginner's Guide
In this simple program that prints "Tutor Joe's" on the screen. Since it's a very simple
program, this program is often used to introduce a new programming language to
beginners.
In JavaScript, you can use the alert() function to display an alert box with a message to
the user. The basic syntax for the alert() function is as follows:
Source Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tutor Joes</title>
</head>
<body>
<script>
alert("Tutor Joes");
</script>
</body>
</html>
This will display an alert box with the message "Tutor Joes" and an OK button that the
user must click to close the alert box.You can also use the prompt() function to display
an input box and get input from the user.
4
Mastering the JavaScript Console: Tips and Tricks
for Debugging and Development
In javascript, the console is an object which provides access to the browser debugging
console. We can open a console in web browser. The console object provides us with
several different methods :
• log()
• error()
• warn()
• clear()
• time() and timeEnd()
• table()
• count()
• custom console logs
The JavaScript console is a built-in object in the browser that provides access to the
browser's developer console. The developer console is a tool that allows developers to
view and debug their code, as well as run JavaScript commands directly in the browser.
The console object provides a number of methods for logging information to the console,
such as console.log(), console.info(), console.warn(), and console.error(). These
methods can be used to output data to the console, which can be useful for debugging
and understanding the behavior of a JavaScript application. Additionally, the console
object also provides methods for measuring performance, such as console.time() and
console.timeEnd(), and for grouping and collapsing output in the console
using console.group() and console.groupEnd().
Source Cod
script.js
5
console.error("Custom Sample Error");
console.warn("Custom Sample Error");
console.clear();
console.time("Timer");
for(i=0;i<10;i++)
{
console.log(i);
}
console.timeEnd("Timer");
One of the features that came with ES6 is the addition of let and const, which can be
used for variable declaration.
• The var keyword is used in all JavaScript code from 1995 to 2015.
• The let and const keywords were added to JavaScript in 2015.
• If you want your code to run in older browser, you must use var.
var
Variable means anything that can vary. In JavaScript, a variable stores the data value
that can be changed later on.
Use the reserved keyword var to declare a variable in JavaScript.
let
const
6
• const have Block Scope.
Data types in JavaScript describe the different types or kinds of data that you will be
working with and storing in variables. It's important that you learn each of these data
types because otherwise data can get stored in an improper format which will result in
issues in your code later on.n JavaScript, data types are used to classify different types
of data and define the type of values that a variable can hold. The main data types in
JavaScript include:
Primitive data types: These are the basic data types that include numbers, strings,
booleans, and special values like null and undefined.
7
Data Type Description
Null and null and undefined stand for empty. That means they have no value assigned to them.
Undefined
Symbols Symbol is a primitive data type of JavaScript.It's a very peculiar data type. Once you
create a symbol, its value is kept private and for internal use.
Array An array is a type of object used for storing multiple values in single variable.
Date JavaScript does not have a date data type. However, you can use the Date object and its
methods to work with dates and times in your applications.
JavaScript is a loosely typed language, which means that the data type of a variable
does not have to be explicitly declared. Instead, JavaScript automatically determines the
data type of a variable based on the value assigned to it. However, it's a good practice to
be aware of the data types in JavaScript as you work with variables and write your code.
In addition to these basic data types, JavaScript also has some special data types like
Symbol and bigInt, which are used for specific purposes.
Source Code
script.js
8
Symbols E6
Array
Object Literals
Date
*/
var a=25.5;
var fname="Tutor Joes";
var isMarried=true;
var phone=null;
let b;
console.log(typeof b);
//ES6 2015
const s1=Symbol() //dlkfngsgs6565df6
console.log(s1)
const s2=Symbol() //fdfgdfg4345345
console.log(s2)
console.log(s1==s2);
var courses=['C','C++','Java'];
var student={
'name':'Joes',
'age':22
}
var d=new Date();
console.log(d);
console.log(typeof d);
9
Type Conversion in JavaScript: How to Convert and
Cast Data Types
In JavaScript, type conversion is the process of changing the data type of a variable or a
value. This can be done using various built-in functions and methods.
Few Examples of Type Conversion
• Strings to Numbers
• Numbers to Strings
• Dates to Numbers
• Numbers to Dates
• Boolean to Numbers
• Numbers to Boolean
JavaScript also has some unary operators that perform type conversion
10
It is also possible to convert a value to a different type using the valueOf() and toString()
methods.
JavaScript also has some automatic type coercion which happens when different types
are being used together in an operation. For instance, if a string is added to a number,
JavaScript will convert the string to a number before performing the addition.
It's important to keep in mind that type conversion can lead to unexpected results if not
handled properly.
Source Code
script.js
//Type Conversion
let a;
//Others to String
a=25;
console.log(a,typeof a);
a=String(25);
console.log(a,typeof a);
a=25.5;
console.log(a,typeof a);
a=String(25.5);
console.log(a,typeof a);
a=true;
console.log(a,typeof a);
a=String(true);
console.log(a,typeof a);
a=new Date();
console.log(a,typeof a);
a=String(a);
console.log(a,typeof a);
a=[1,2,3,4,5]
console.log(a,typeof a);
a=String(a);
console.log(a,typeof a);
a=25
console.log(a,typeof a);
a=a.toString();
console.log(a,typeof a);
//String to number
a="1234"
console.log(a,typeof a);
a=Number(a);
console.log(a,typeof a);
a=true;
11
console.log(a,typeof a);
a=Number(a);
console.log(a,typeof a);
a=[1,2,3,4,5];
console.log(a,typeof a);
a=Number(a);
console.log(a,typeof a);
a="Tutor Joes";
console.log(a,typeof a);
a=Number(a);
console.log(a,typeof a);
a='35';
console.log(a,typeof a);
a=parseInt(a);
console.log(a,typeof a);
a='35.55';
console.log(a,typeof a);
a=parseInt(a);
console.log(a,typeof a);
a='35.55';
console.log(a,typeof a);
a=parseFloat(a);
console.log(a,typeof a);
Type Coercion refers to the process of automatic or implicit conversion of values from
one data type to another. This includes conversion from Number to String, String to
Number, Boolean to Number etc. when different types of operators are applied to the
values.
Type coercion in JavaScript refers to the process of converting a value from one data
type to another automatically. This happens when different data types are used in the
same operation or when a value is compared to a value of a different data type.
For example, when a string is added to a number, JavaScript will automatically convert
the string to a number before performing the addition. Similarly, when a non-boolean
value is used in a boolean context, JavaScript will convert the value to a boolean using a
set of rules.
12
JavaScript uses a set of rules to determine the type of a value when performing type
coercion, these rules are called type coercion rules. For example, in JavaScript empty
string, 0, null, undefined, NaN are considered as falsy values, and all other values are
considered as truthy.
Type coercion can also occur when comparing values of different data types. For
example, when comparing a string to a number, JavaScript will convert the string to a
number before making the comparison.
It's important to be aware of type coercion when writing JavaScript code, as it can lead
to unexpected behavior if not handled properly. To avoid type coercion issues, it's best
practice to explicitly convert the data types when necessary.
Source Code
script.js
//Type Coercion
let a="25";
let b=10;
console.log(a+b);
a=Number("25");
b=10;
console.log(a+b);
no Operator Usage
1. + Addition
2. - Subtraction
3. * Multiplication
4. ** Exponentiation (2016)
13
no Operator Usage
5. / Division
6. % Modulus (Remainder)
7. ++ Increment
8. -- Decrement
• Addition (+): This operator is used to add two or more numbers together. For
• Subtraction (-): This operator is used to subtract one number from another. For
• Multiplication (*): This operator is used to multiply two or more numbers together.
• Division (/): This operator is used to divide one number by another. For example,
• Modulus (%): This operator is used to find the remainder when one number is
Source Code
script.js
//Arithmetic Operation
let a=100;
14
let b=20;
let c;
c=a+b;
c=a-b;
c=a*b;
c=a/b;
c=a%b;
c=2**3;//2016
c=++a;
c=--b;
console.log(c);
The above code is written in JavaScript and it performs various arithmetic operations on
two variables, a and b. The variables a and b are declared using the let keyword and are
assigned the values 100 and 20, respectively.
A new variable c is declared using the let keyword and is used to store the result of the
arithmetic operations.
The first operation is the addition of a and b and the result is assigned to c. Then the
subtraction of b from a and the result is assigned to c. Then the multiplication
of a and b and the result is assigned to c. Then the division of a by b and the result is
assigned to c. Then the modulus of a by b and the result is assigned to c.
Then the operation 2 raised to the power of 3, which gives the result 8. Then the
operation of incrementing the value of a and the result is assigned to c. Then the
operation of decrementing the value of b and the result is assigned to c.
Finally, the console.log() function is used to output the final value of c to the console,
which will be the result of the last operation performed, which is decrementing the value
of b.
15
Understanding the Power of Shorthand Assignment
Operators in JavaScript
In JavaScript, assignment operators are used to assign values to variables. The basic
assignment operator is the "=" sign, which assigns the value on the right side of the
operator to the variable on the left side. There are also several shorthand assignment
operators that can be used to perform an operation and assignment in one step. These
include
no Operator Usage
1. = Assigns a value
4. *= Multiplies a variable.
5. /= Divides a variable.
• Addition assignment (+=): adds the right-side value to the left-side variable and
• Subtraction assignment (-=): subtracts the right-side value from the left-side
16
• Division assignment (/=): divides the left-side variable by the right-side value and
• Modulus assignment (%=): finds the remainder when the left-side variable is
divided by the right-side value and assigns the result to the left-side variable.
• Exponentiation assignment (**=): raises the left-side variable to the power of the
It's important to note that these shorthand assignment operators only work with
variables, they can not be used with literals. Additionally, the shorthand assignment
operators follow the order of precedence of the mathematical operation they are
performing.
Another important point is that you should be careful about using the assignment
operator within the conditional statements because it can lead to unexpected results if
not used correctly.
Source Code
script.js
//Assignment Operators
let a=10;
//a=a+5; //+=
a+=5;//15
a-=5;//10
a*=5;//50
a/=5;//50
a%=5;//0
console.log(a);
This code uses the shorthand assignment operators to perform arithmetic operations
and assignment in one step.
• The next line uses the "+=" shorthand operator to add 5 to the current value of a
and assigns the result back to a. This is equivalent to writing a = a + 5; and the
• The next line uses the "-=" shorthand operator to subtract 5 from the current
value of a and assigns the result back to a. The value of a will be 10.
17
• The next line uses the "*=" shorthand operator to multiply the current value of a
• The next line uses the "/=" shorthand operator to divide the current value of a by
• The next line uses the "%=" shorthand operator to finds the remainder when the
current value of a is divided by 5 and assigns the result back to a. The value of a
will be 0.
console, which is 0.
So the final value of a will be 0, because all the operation are performed on the
value of a and the last operation is a%=5 which returns the remainder of a
divided by 5 which is 0.
In JavaScript, comparison operators are used to compare two values and return a
Boolean value (true or false) depending on the result of the comparison. The basic
comparison operators include
Equality (==): This operator compares two values to see if they are equal.
Inequality (!=): This operator compares two values to see if they are not equal.
=== operator, on the other hand, is a strict equality operator and does not perform type
coercion. It will only return true if the values being compared have the same type and
value.
18
no Operator Usage
1. == equal to
3. != not equal
Source Code
script.js
//Comparison Operators
let a=10;
let b="25";
console.log(a==b);
console.log(a===b);
console.log(a!=b);
console.log(a!==b);
The first console.log statement will output false because the == operator compares the
values of the variables, and 10 is not equal to "25".
The second console.log statement will output false as well because the === operator
compares the values and types of the variables, and 10 is not equal to "25" in both value
and type.
The third console.log statement will output true because the != operator returns the
opposite of the == operator, so 10 is not equal to "25".
The fourth console.log statement will output true as well because the !== operator
returns the opposite of the === operator, so 10 is not equal to "25" in both value and
type.
19
Exploring the World of Relational Operators in
JavaScript
In JavaScript, there are several relational operators that can be used to compare values
and determine the relationship between them. When using these operators, the
expressions on either side of the operator will be evaluated and compared to determine
if the relationship between them is true or false
no Operator Usage
Greater than (>): This operator compares two values and returns true if the left-side
value is greater than the right-side value and false if it is not.
Less than (<): This operator compares two values and returns true if the left-side value is
less than the right-side value and false if it is not.
Greater than or equal to (>=): This operator is used to compare two values and
determine if the first value is greater than or equal to the second value. If the first value
is greater than or equal to the second value, the operator returns true. If the first value is
less than the second value, the operator returns false.
Less than or equal to (<=): This operator is used to compare two values and determine if
the first value is less than or equal to the second value. If the first value is less than or
equal to the second value, the operator returns true. If the first value is greater than the
second value, the operator returns false.
Source Code
script.js
20
//Relational Operators in JavaScript
/*
> greater than
< less than
>= greater than or equal to
<= less than or equal to
*/
let a=10;
let b=20;
console.log("Greater : ",a>b);
console.log("Lesser : ",a<b);
console.log("Greater Than Equal : ",a>=b);
console.log("Greater Than Equal : ",a<=b);
The first console.log statement will output "Greater : false" because the value of a is not
greater than the value of b.The second console.log statement will output "Lesser : true"
because the value of a is less than the value of b.The third console.log statement will
output "Greater Than Equal : false" because the value of a is not greater than or equal to
the value of b.The fourth console.log statement will output "Greater Than Equal :
true" because the value of a is less than or equal to the value of b.
In JavaScript, there are several logical operators that can be used to combine and
evaluate multiple expressions. These operators include:
1. && and
2. || or
3. ! not
The && operator compares two expressions and returns true only if both expressions are
true. The || operator compares two expressions and returns true if either or both
21
expressions are true. The ! operator negates the value of a single expression, so if the
expression is true, it returns false and if the expression is false, it returns true.
Source Code
script.js
//Logical Operators in JavaScript
/*
&& logical and
|| logical or
! logical not
*/
//35-100
let mark=45;
let a=5;
//2,5
console.log(a==2 || a==5);
a=false;
console.log(!a);
The Below code uses logical operators in JavaScript to perform different comparisons
and return a Boolean value (true or false).
The first line of code uses the logical and operator (&&) to check if the value of the
variable mark is greater than or equal to 35 and less than or equal to 100.
The && operator checks if both conditions are true, and if so, returns true. In this case,
since 45 is greater than or equal to 35 and less than or equal to 100, the console will
log true.
The second line of code uses the logical or operator (||) to check if the value of the
variable a is equal to 2 or equal to 5. The || operator checks if either of the conditions are
true, and if so, returns true. In this case, since 5 is equal to 5, the console will log true.
The last line of code uses the logical not operator (!) to check the opposite of the value
of the variable a. The ! operator inverts the Boolean value of the variable, so if a is false,
the console will log true.
22
Strict Equality or Identity Operators in JavaScript
In JavaScript, identity operators are used to compare the equality of two values while
also considering their data types. There are two identity operators:
o The strict equality operator (===) checks for equality between two values
while considering both their values and data types. It returns true if both
the values and data types are identical, and false otherwise
o The equality operator (==) also checks for equality between two values,
but it performs type coercion if the data types are different. It tries to
convert one or both operands to the same type before making the
comparison.
Source Code
script.js
//strict equality or Identity Operator
let a=10;
console.log(a);
let b='10';
console.log(a==b);
console.log(a===b);
23
Ternary Operators in JavaScript
Syntax
Source Code
script.js
//Simple Example
const age=22;
const result=age>=18?"Eligible":"Not Eligible";
console.log(result);
user={'name':'Tiya','age':25};
console.log(user);
console.log(user.name);
const greeting=(user)=>{
const name=user.name?user.name:"No Name";
return "Hello "+name;
}
console.log(greeting(user));
24
//Conditional chains
/*
avg >=90 A grade
avg >=80 B grade
C grade
*/
const avg=75;
const grade=avg>=90? "A Grade":avg>=80? "B Grade":"C Grade";
console.log("Grade : ",grade);
Bitwise operators in JavaScript are used to manipulate the individual bits of integer
values at the binary level. These operators perform bit-level operations on the binary
representations of the values. Bitwise operations are commonly used in low-level
programming, cryptography, and certain optimization techniques.
no Operator Usage
25
script.js
//Bitwise Operators in js
//&
let a=12;//1100
let b=24;//11000
console.log(a&b);
//&=
a&=b;
console.log(a);
// | (Bitwise or)
a=12;//1100
b=24;//11000
console.log(a|b);
//|=
a|=b;
console.log(a);
// ~ ~a = -a-1
a=12; //-25-1=-26
console.log(~a);
// ^
a=12;
b=6;
console.log(a^b);
//<<
a=5;
b=2;
console.log(a<<b);
a<<=b;
console.log(a);
//>>
a=8;
b=2;
console.log(a>>b);
a>>=b;
console.log(a);
// >>>
a=-11;
b=2;
/*
0010
0011
----
0010
0000 1100 12
0001 1000 24
-----------------
0000 1000 8
0000 1100 12
0001 1000 24
-----------------
0001 1100 8
*/
26
Nullish Coalescing Operators in JavaScript
The nullish coalescing operator is represented by ??, and it returns the right-hand
operand when the left-hand operand is either null or undefined. Otherwise, it returns the
left-hand operand.
Syntax
Source Code
script.js
const b=null??45;
console.log(b);
//??=
const user={'name':'joes'};
console.log(user);
console.log(user.name);
user.city??='Salem';
console.log(user.city);
console.log(user);
27
Increment or Decrement Operators in JavaScript
The increment (++) and decrement (--) operators in JavaScript are used to increase or
decrease the value of a variable by 1, respectively. They are unary operators, meaning
they work on a single operand. The increment (++) and decrement (--) operators can be
used in two forms: postfix and prefix. The difference lies in when the increment or
decrement operation takes place in relation to the variable.
o The postfix increment (x++) and postfix decrement (x--) operators first
return the original value of the variable and then increment or decrement
the variable by 1.
o The prefix increment (++x) and prefix decrement (--x) operators first
value.
Source Code
script.js
// Increment (++) or Decrement (--)
let a=1;
a++; //a=a+1
console.log(a);
let b=5;
b--; //b=b-1;
console.log(b);
/*
PostFix Increment a++
Prefix Increment ++a
*/
let x=3;
const y=x++; //3
console.log("X : ",x,"Y : ",y);
let i=3;
const j=++i;
console.log("I : ",i,"J : ",j);
28
If Statement in JavaScript
The "if" statement is used to make decisions based on the evaluation of a condition. It
allows you to execute a block of code if a given condition is true. If the condition is false,
the code inside the "if" block is skipped, and the program continues with the next
statement after the "if" block.
Syntax :
if (condition)
{
// Code to be executed if the condition is true
}
The "condition" is an expression that evaluates to a Boolean value (true or false). If the
condition is true, the code inside the curly braces {} is executed. If the condition is false,
the code inside the "if" block is skipped.
Source Code
script.js
/*
if(condition)
{
.....
}
*/
let age=prompt("Enter Your Age : ");
if(age!=null && age>=18)
{
console.log("You are Eligible for Vote..");
}
The "if-else" statement is used to implement conditional logic, allowing you to execute
different blocks of code based on whether a given condition is true or false. If the
condition in the "if" block is true, the code inside the "if" block is executed. If the
condition is false, the code inside the "else" block is executed.
29
Syntax :
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
/*
if(condition){
-----
}
else{
-----
}
*/
let age=prompt("Enter Your Age : ");
if(age!=null && age>=18)
{
console.log("You are Eligible for Vote..");
}
else
{console.log("You are Not Eligible for Vote..");}
The "else if" statement is used to implement multiple conditional branches in the
decision-making process. It allows you to check for additional conditions after the initial
"if" condition, and if the previous "if" condition is false, it evaluates the "else if" conditions
one by one until it finds a true condition or reaches the "else" block.
Syntax :
if (condition) {
// Code to be executed if the condition1 is true
} else if (condition2) {
// Code to be executed if condition2 is true
} else if (condition3) {
// Code to be executed if condition3 is true
} else {// Code to be executed if none of the above conditions are true
}
30
script.js
/*
if(cond)
{
----
}
else if(cond)
{
----
}
else
{
---
}
*/
//Example-1
let number=0;
if(number<0)
{
console.log(number+" is negative Number");
}
else if(number>0)
{
console.log(number+" is Positive Number");
}
else
{
console.log("Given number is zero");
}
//example-2
/*
avg=87;
90-100 A Grade
80-89 B Grade
70-79 C Grade
<70 D Grade
*/
let avg=45;
31
Nested If Statement in JavaScript
Nested "if" statement is an "if" statement that is placed inside another "if" or "else" block.
It allows you to create more complex decision-making logic by handling multiple
conditions and their respective code blocks.
Syntax:
if (outerCondition)
{
Code to be executed if outerCondition is true
if (innerCondition1) {
// Code to be executed if innerCondition1 is true
} else {
// Code to be executed if innerCondition1 is false
}
if (innerCondition2) {
// Code to be executed if innerCondition2 is true
} else {
// Code to be executed if innerCondition2 is false
}
} else {
Code to be executed if outerCondition is false
}
script.js
//Nested If Statement
/*
if(cond)
{
if(cond)
{
---
}
}
32
*/
let english=95,tamil=98,maths=75;
let total,avg;
total=english+tamil+maths;
avg=total/3;
console.log("Total : "+total);
console.log("Average : "+avg.toFixed(2));
The "switch" statement provides a way to execute different blocks of code based on the
value of an expression. It offers an alternative to multiple nested "if-else" statements
when you have several possible conditions to check.
Syntax:
switch (expression) {
case value1:
// Code to be executed if the expression is equal to value1
break;
case value2:
// Code to be executed if the expression is equal to value2
break;
// More cases can be added here
default:
// Code to be executed if the expression does not match any of the cases
33
break;
}
script.js
/*
switch(choice)
{
case choice:
-----
break;
case choice:
-----
break;
default:
----
break;
}
*/
let num=5;
switch(num)
{
case 1:
console.log("One");
break;
case 2:
console.log("Two");
break;
case 3:
console.log("Three");
break;
default:
console.log("Invalid Input");
break;
}
34
Syntax:
switch (expression) {
case value1:
case value2:
case value3:
// Code to be executed for value1, value2, and value3
break;
case value4:
// Code to be executed for value4
break;
// More cases can be added here
default:
// Code to be executed if the expression does not match any of the cases
break;
}
script.js
let letter='p';
switch(letter)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
console.log(letter+" is an Vowel");
break;
default:
console.log(letter+" is not a Vowel");
break;
}
35
While Loop in JavaScript
a while loop is a control flow statement that allows you to repeatedly execute a block of
code as long as a specified condition evaluates to true. It is one of the fundamental loop
constructs in JavaScript and is used when the number of iterations is not known
beforehand.
Syntax:
while (condition) {
// Code to be executed as long as the condition is true
}
Source Code
script.js
let i = 0;
while (i < 10) {
console.log(i);
i++;
}
In JavaScript, a "do-while" loop is a control flow statement that allows you to repeatedly
execute a block of code as long as a specified condition is true. It is similar to the "while"
loop, but with one key difference: the "do-while" loop guarantees that the code inside the
loop is executed at least once, even if the condition is false from the beginning.
Syntax:
do {
// Code to be executed
} while (condition) ;
36
Source Code
script.js
/*
do {
} while (condition);
*/
let table=88;limit=5;i=1;
do
{
console.log(table+" X "+i+" = "+(table*i));
i++;
}while(i<=limit);
In JavaScript, a "for" loop is a control flow statement that allows you to repeatedly
execute a block of code for a specific number of iterations. It is one of the most
commonly used loops and is particularly useful when the number of iterations is known
or when you want to iterate over elements in an array or other data structures.
Syntax:
for (initialization; condition; update) {
// Code to be executed for each iteration
}
• Initialization: This part is executed once before the loop starts. It is typically used
37
• Condition: The loop continues as long as the condition is true. Before each
iteration, the condition is evaluated. If the condition is false, the loop terminates,
and the program continues with the next statement after the loop.
• Update: This part is executed after each iteration of the loop. It is typically used
Source Code
script.js
/*
for (initialize variable; condition; statement) {
// code to be executed
}
*/
for(let i=1;i<=10;i++)
{
console.log(i);
}
let arr=[];
for(let i=0;i<100;i+=2)
{
arr.push(i);
}
console.log(arr);
console.log(arr[49]);
In JavaScript, a nested "for" loop is a loop inside another loop. It allows you to create
more complex looping structures to handle multidimensional data or perform repetitive
tasks involving multiple sets of data.
Syntax:
for (let i = 0; i < outerLength; i++)
{
38
// Code to be executed in the outer loop
for (let j = 0; j < innerLength; j++)
{
// Code to be executed in the inner loop
}
}
Source Code
script.js
let nums=[];
for(let i=0;i<3;i++) //i=0 0<3 1<3
{
nums.push([]); //nums[0] nums[1]
for(let j=0;j<3;j++)
{
nums[i].push(j);//num[1]={0,1,2}
}
}
console.log(nums);
console.table(nums);
Syntax:
for (variable of iterable) {
// Code to be executed for each iteration
}
39
Source Code
script.js
for(let i=0;i<names.length;i++)
{
console.log(names[i]);
}
console.log("For of Loop : ")
for(let name of names){
console.log(name);
}
In JavaScript, the "for...in" loop is a traditional iteration method used to loop over the
properties of an object. It allows you to iterate through the keys or property names of an
object, rather than the values. The "for...in" loop is particularly useful when you need to
access the keys or properties of an object and perform operations on them.
Syntax:
for (variable in object) {
// Code to be executed for each property of the object
}
Source Code
script.js
let user = {
name: "Tutor Joes",
age: 35,
city: "Salem",
contact: "9043017689",
};
40
Looping over objects by converting to an array in
JavaScript
In JavaScript, you can loop over objects by converting them into an array of key-value
pairs using various methods. Once the object is converted into an array, you can use
standard array iteration methods like "for...of" loop, "forEach" method, or other array
iteration techniques to access and process the key-value pairs.
Source Code
script.js
let user = {
name: "Tutor Joes",
age: 35,
city: "Salem",
contact: "9043017689",
};
let arr_keys=Object.keys(user);
console.table(arr_keys);
let arr_values=Object.values(user);
console.table(arr_values);
for(let i=0;i<arr_keys.length;i++)
{
console.log(arr_keys[i]+" : "+arr_values[i]);
//console.log(user[arr_keys[i]]);
}
Break in JavaScript
In JavaScript, the "break" statement is a control flow statement that allows you to exit or
terminate a loop or switch statement prematurely. When the "break" statement is
encountered within a loop or switch, the program immediately exits that loop or switch,
and execution continues with the next statement after the loop or switch block.
Source Code
script.js
41
for(let i=1;i<=10;i++)
{
console.log(i);
if(i==4){
break;
}
}
Continue in JavaScript
In JavaScript, the "continue" statement is a control flow statement that allows you to
skip the rest of the current iteration of a loop and continue with the next iteration. When
the "continue" statement is encountered within a loop, it jumps to the next iteration,
bypassing any code following the "continue" statement within that iteration.
Source Code
script.js
for(let i=1;i<=10;i++)
{
if(i==4){
continue;
}
console.log(i);
}
for(let i=1;i<=10;i++)
{
if(i%2==0){
continue;
}
console.log(i);
}
In JavaScript, labeled blocks are a way to label a block of code using an identifier
(label). These labels are used in conjunction with statements like "break" and "continue"
to control the flow of execution within nested loops or blocks.
Syntax:
labelName: {
// Code block or statements
}
42
Source Code
script.js
let groups = [
["Ram", "Sam", "Ravi"],
["Kumar", "Tiya", "Sundar"],
["Rajesh", "Sara", "Rahul"],
];
JavaScript provides a built-in Math object that contains various mathematical functions
and constants that can be used in your code. Some of the commonly used mathematical
functions in JavaScript are
43
• Math.floor(x): rounds the number x down to the nearest integer.
• Math.round(x): rounds the number x to the nearest integer.
• Math.sqrt(x): returns the square root of x.
• Math.pow(x, y): returns the value of x raised to the power of y.
• Math.max(x1, x2, ...): returns the largest of zero or more numbers.
• Math.min(x1, x2, ...): returns the smallest of zero or more numbers.
• Math.random(): returns a random number between 0 and 1.
• Math.sin(x): returns the sine of x (x is in radians).
• Math.cos(x): returns the cosine of x (x is in radians).
• Math.tan(x): returns the tangent of an angle x (x is in radians).
• Math.log(x): returns the natural logarithm (base e) of x.
• Math.log10(x): returns the common logarithm (base 10) of x.
• Math.exp(x): returns the value of Ex.
The Math object also provides some mathematical constants like Math.PI, Math.E and
Math.LN2, Math.LN10, Math.LOG2E, Math.LOG10E etc.
It's important to note that the Math object is a static object, which means that you do not
need to create an instance of the object in order to use.
Source Code
This code demonstrates the use of the built-in Math object in JavaScript, which provides
various mathematical functions and constants that can be used in your code.
• The first line assigns the value of PI to the variable c using the Math.PI constant.
• The next line assigns the value of E to the variable c using the Math.E constant.
• The next line uses the Math.round() function to round the number 5.8 to the
• The next line uses the Math.floor() function to round the number 5.58 down to the
• The next line uses the Math.ceil() function to round the number 5.58 up to the
• The next line uses the Math.sqrt() function to find the square root of 90, which is
44
• The next line uses the Math.abs() function to find the absolute value of -45, which
• The next line uses the Math.trunc() function to truncate the number 4.9 and
returns the integer part, which is 4. The result is assigned to the variable c.
• The next line uses the Math.pow() function to find the power of 2 raised to 4,
• The next line uses the Math.min() function to find the minimum number among
10, 50, 5, 45, and 8, which is 5. The result is assigned to the variable c.
• The next line uses the Math.max() function to find the maximum
script.js
// Math Object
c=Math.PI;
c=Math.E;
c=Math.round(5.8);
c=Math.floor(5.58);
c=Math.ceil(5.58);
c=Math.sqrt(90);
c=Math.abs(-45);
c=Math.trunc(4.9);//Return Integer only
c=Math.pow(2,4);
c=Math.min(10,50,5,45,8);
c=Math.max(10,50,5,45,8);
c=Math.random();
c=Math.floor((Math.random()*50+1));
c=Math.sign(1); //Return Neg=-1 Zero=0 Pos=1
c=Math.sin(90);
c=Math.cos(90);
c=Math.log(1);
c=Math.log2(10);
c=Math.log10(10);
console.log(c)
45
String Functions in JavaScript
These are some of the common string functions in javascript, however, there are many
more string functions available.
//Concatenation
let c=first_name+" "+last_name;
console.log("Concatenation : "+c);
//concat
c=first_name.concat(' ',last_name);
console.log("Concat : "+c);
//append
c="Tutor ";
c+="Joes";
console.log("Append : "+c);
//Escaping
c='She Can\'t run';
console.log(c);
46
//Length
c=first_name.length;
console.log("Length : "+c);
//Change Case
c=first_name.toUpperCase();
console.log("Uppercase : "+c);
c=first_name.toLowerCase();
console.log("Lowercase : "+c);
c=first_name.indexOf('T');
console.log("indexOf T : "+c);
c=first_name.lastIndexOf('T');
console.log("lastIndexOf T : "+c);
c=first_name.charAt(1);
console.log("charAt 1 : "+c);
c=first_name.charCodeAt(1);
console.log("charCodeAt 1 : "+c);
c=first_name.substr(0,3);
console.log("substr : "+c);
//Substring
let text = "01234567890";
c=text.substring(0,4)
console.log("Substring : "+c);
c=text.substring(4);
console.log("Substring : "+c);
c=text.substring(4,0);
console.log("Substring : "+c);
c=text.substring(25,30);
console.log("substring Invalid Length : "+c);
c=text.substring(-3);
console.log("-3 : "+c);
//Slice
c=text.slice(2,4);
console.log("slice : "+c);
c=text.slice(4,2);
console.log("slice : "+c);
c=text.slice(25,30);
console.log("slice Invalid Length : "+c);
c=text.slice(-5)
console.log("slice -5: "+c);
//Split in JS
let a="Tutor Joes Computer Education";
c=a.split(" ");
console.log("Split : "+c);
console.table(c);
//replace in js
a="I am from Salem";
console.log("Before Replace : "+a);
c=a.replace('Salem','Chennai');
console.log("After Replace : "+c);
47
//includes in js
const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));
console.log(pets.includes('rat'));
//trim in js
a=" Joes ";
console.log("Before Trim : "+a.length);
a=a.trim();
console.log("After Trim : "+a.length);
//padStart padEnd
a="5";
a=a.padStart(4,0);
console.log(a);
a="5";
a=a.padEnd(4,0);
console.log(a);
a="5";
a=a.padEnd(4,'$');
console.log(a);
//String.fromCharCode()
console.log(String.fromCharCode(65,66,67,68,97,98,122));
1. Concatenation: The + operator is used to concatenate two strings and store the
result in the variable c. The concat() method is also used to concatenate two
2. Append: The += operator is used to append a string to the existing string, and
3. Escaping: The \' is used to escape the single quote in the string.
4. Length: The length property is used to find the number of characters in a string
48
5. Change Case: The toUpperCase() method is used to convert a string to
lowercase letters.
6. IndexOf and LastIndexOf: The indexOf() method returns the position of the first
7. charAt and charCodeAt: The charAt() method returns the character at the
specified index in a string, and the charCodeAt() method returns the Unicode of
8. Substring and Substr: The substring() method returns the characters in a string
between two specified indices, and the substr() method returns the characters in
a string beginning at a specified start position and through the specified number
of characters.
10. Split: The split() method is used to split a string into an array of substrings based
on a specified separator.
11. Replace: The replace() method is used to replace all occurrences of a specified
12. Includes: The includes() method is used to check if an array includes a certain
element.
13. Trim: The trim() method is used to remove whitespaces from both ends of a
string.
14. PadStart and PadEnd: The padStart() method is used to pad the start of a string
with a specified number of characters, and the padEnd() method is used to pad
49
15. Long literal strings: There are two ways to create a long literal string in javascript.
Template Literals use back-ticks (` `) rather than the quotes (" ") to define a string
Quotes Inside Strings
With template literals, you can use both single and double quotes inside a string.
Multiline Strings
In JavaScript, template literals are a way to create strings that include expressions. They
are enclosed by backticks (`) rather than single or double quotes. Expressions within
template literals are denoted by a dollar sign and curly braces (${expression}).
Template literals also support multiline strings and string interpolation, making it more
powerful than the traditional string concatenation way.
50
NORMAL FORMAT
The Below code creates four variables: full_name, age, city, and role, and assigns them
string values. Then it creates a variable called output and assigns it an empty string.
The output variable is then assigned a string which contains an HTML table, where the
values of the full_name, age, city, and role variables are used to populate the table cells.
The string uses the traditional string concatenation method to combine the static HTML
table structure with the dynamic variable values.
ES5
In this example,the output variable is assigned a string that contains an HTML table,
where the values of the full_name, age, city, and role variables are used to populate the
table cells. The string uses the traditional string concatenation method to combine the
static HTML table structure with the dynamic variable values.
This Code explain the output variable is first assigned an empty string and then the
string is concatenated by using the + operator. The output variable starts with
an <hr> tag and then it's followed by the table structure. This way the table will be
separated with a horizontal line.You can insert this variable into an HTML element and it
will be rendered as a table with the values inside the cells separated by horizontal line.
full_name, age, city, and role, and assigns them string values. Then it creates a variable
called output and assigns it an empty string.
The output variable is then assigned a string which contains an HTML table, where the
values of the full_name, age, city, and role variables are used to populate the table cells.
This time, it uses the template literals feature of es6 to create the table. Template literals
are enclosed by backticks (`) rather than single or double quotes. Expressions within
template literals are denoted by a dollar sign and curly braces (${expression}).
In this example, the template literals is used to create the table structure, it starts with
an <hr> tag and then it's followed by the table structure, where the values are inserted
using the expressions inside the curly braces ${}.
In the second row of the table, the age value is compared with 25, if it's greater than 25,
it will return "Good" otherwise "Bad" will be returned. This is a ternary operator that is
being used to check the condition.
51
Source Code
let full_name="Tutor Joes";
let age="12";
let city="Salem";
let role="CEO Tutor Joes";
let output="";
output="<table
border='1'><tr><th>Name</th><td>"+full_name+"</td></tr><tr><th>Age</th><td>
"+age+"</td></tr><tr><th>City</th><td>"+city+"</td></tr><tr><th>Role</th><t
d>"+role+"</td></tr></table>";
//es5
output+="<hr><table border='1'>"+
"<tr><th>Name</th><td>"+full_name+"</td></tr>"+
"<tr><th>Age</th><td>"+age+"</td></tr>"+
"<tr><th>City</th><td>"+city+"</td></tr>"+
"<tr><th>Role</th><td>"+role+"</td></tr>"+
"</table>";
//es6
output+=`<hr>
<table border='1'>
<tr><th>Name</th><td>${full_name}</td></tr>
<tr><th>Age</th><td>${age>=25?"Good":"Bad"}</td></tr>
<tr><th>City</th><td>${city}</td></tr>
<tr><th>Role</th><td>${role}</td></tr>
</table>`;
document.body.innerHTML=output;
The Array in JavaScript is a global object which contains a list of items. It is similar to
any variable, in that you can use it to hold any type of data.
This is zero-based, which means that the index of the first element is 0. An element
inside an array can be of any type, and different elements of the same array can be of
different types : string, boolean, even objects or other arrays.
52
length() concat() join()
These are just a few examples of the many array functions available in JavaScript, and
there are many more to explore.
Example
let a=[10,20,30,40];
console.log(a);
console.table(a);
console.log(a[1]);
Given an array containing functions and the task is to access its element in different
ways using JavaScript.
53
forEach
Source Code
const number=[1,2,30,4,5,6,7,8,9,10];
//value,index,array
number.forEach((value)=>{
console.log(value);
});
number.forEach((value,index)=>{
console.log("Index : "+index+" Value: "+value);
});
const users =[
{full_name:"Ram",age:12,city:"Salem",salary:10000},
{full_name:"Sam",age:15,city:"Chennai",salary:10500},
{full_name:"Ravi",age:22,city:"Namakkal",salary:12000},
{full_name:"Joes",age:18,city:"Hosur",salary:6000},
{full_name:"Aureen",age:47,city:"Dharmapuri",salary:10000},
{full_name:"Stanley",age:10,city:"Salem",salary:8000},
];
console.table(users);
users.forEach((value)=>{
console.log(value.full_name);
});
map
• Creates a new array from calling a function for every array element.
• Calls a function once for each element in an array.
• Does not execute the function for empty elements.
• Does not change the original array.
Source Code
const numbers=[1,2,3,4,5,6,7,8,9,10];
//map(value,index,array)
let sqrt=numbers.map((value)=>{
return Math.sqrt(value).toFixed(2);
});
console.table(sqrt);
const users =[
{name:"Sam",age:15,city:"Chennai",salary:10500},
{name:"Ravi",age:22,city:"Namakkal",salary:12000},
{name:"Joes",age:18,city:"Hosur",salary:6000},
54
{name:"Aureen",age:47,city:"Dharmapuri",salary:10000},
{name:"Stanley",age:10,city:"Salem",salary:8000},
{name:"Ram",age:12,city:"Salem",salary:10000},
];
console.table(users);
let eligible_status=users.map((user)=>({
/*name:user.name,
age:user.age,
city:user.city,
salary:user.salary,*/
...user,
status:user.age>=18?"Eligible":"Not Eligible"
}));
console.table(eligible_status);
slice
Source Code
const numbers=[1,2,3,4,5,6,7,8,9,10];
//slice(start,end)
console.log(numbers);
console.log("Slice :"+numbers.slice());
console.log("Slice(2) :"+numbers.slice(2));
console.log("Slice(2,5) :"+numbers.slice(2,5));
Splice
method adds and/or removes array elements.This method also overwrites the original
array.
Source Code
/*
Splice is to Remove Elements in array
It will change original array
removed_element=Splice(start,length,new elements)
*/
const n1=[1,2,3,4,5,6,7,8,9,10];
55
const n2=[1,2,3,4,5,6,7,8,9,10];
console.log("Before Splice : "+n2);
removed_elements=n2.splice(2,2);
console.log("Removed Items : "+removed_elements);
console.log("After Splice :"+n2);
const n3=[1,2,3,4,5,6,7,8,9,10];
console.log("Before Splice : "+n3);
removed_elements=n3.splice(2,2,[25,36,45]);
console.log("Removed Items : "+removed_elements);
console.log(n3);
const n4=[1,2,3,4,5,6,7,8,9,10];
console.log("Before Splice : "+n4);
n4.splice(2,0,100,300);
console.log("After Splice :"+n4);
concat
Concatenates (joins) two or more arrays.returns a new array, containing the joined
arrays, It does not change the existing arrays.
Source Code
//concat
const a=[10,20,30];
const b=[40,50,60];
const c=[70,80,90];
let d=a.concat(b);
console.log(d);
d=a.concat(b,c);
console.log(d);
d=a.concat(b,c,25,35,45,55);
console.log(d);
d=a.concat(b,c,25,35,45,55,['a','b','c']);
console.log(d);
console.table(d);
sort
sorts the elements of an array.Mainly this method sorts the elements as strings in
alphabetical and ascending order. And this function overwrites the original array.
Source Code
const names=["Kumar","Aureen","Joes","Zara","Stanley"];
console.log("Before Sort : "+names);
names.sort();
console.log("After Sort : "+names);
const num=[10,100,25,150,45,80,9];
56
console.log("Before Sort : "+num);
num.sort();
console.log("After Sort : "+num);
num.sort((a,b)=>{
return a-b;
});
console.log("Asc Compare Sort : "+num);
num.sort((a,b)=>{
return b-a;
});
console.log("Desc Compare Sort : "+num);
const users =[
{name:"Ram",age:12,city:"Salem",salary:10000},
{name:"Sam",age:15,city:"Chennai",salary:10500},
{name:"Ravi",age:22,city:"Namakkal",salary:12000},
{name:"Joes",age:18,city:"Hosur",salary:6000},
{name:"Aureen",age:47,city:"Dharmapuri",salary:10000},
{name:"Stanley",age:10,city:"Salem",salary:8000},
];
console.table(users);
users.sort((a,b)=>{
return a.age-b.age;
});
console.table(users);
users.sort((a,b)=>{
if(a.name>b.name) return 1;
if(a.name<b.name) return -1;
return 0;
});
console.table(users);
fill
The fill() method fills specified elements in an array with a value.Start and end position
can be specified. If not, all elements will be filled.
Source Code
//Fill(value,start,end)
let n=[1,2,3,4,5,6]
includes
57
• This is also case sensitive.
Source Code
//Includes(value,start_index)
const products = ["Pen", "Pencil", "Eraser", "Box", "Pen"];
let result = products.includes("Pen");
console.log(result);
result = products.includes("Scale");
console.log(result);
result = products.includes("Pencil", 2);
console.log(result);
join()
The join() function in JavaScript is a method of the Array object, it is used to join all
elements of an array into a single string. The elements of the array are separated by a
specified delimiter or separator, which can be a string or a character.
It's important to note that this method will not work if the array contains undefined or null
elements. If it's possible that some elements in the array are undefined or null, it's a
good practice to filter them before using the join function.
Source Code
//array.join(separator)
const products = ["Pen", "Pencil", "Eraser", "Box"];
console.log(products);
The above code to creates an array of strings called products which contains four
elements: "Pen", "Pencil", "Eraser", and "Box".
The first console.log() statement simply outputs the array itself to the console. The
second console.log() statement calls the join() method on the products array with no
argument, which means it uses the default separator, which is a comma (,). This will
58
output the elements of the array as a single string with commas separating each
element: "Pen,Pencil,Eraser,Box"
The third console.log() statement calls the join() method on the products array and
passes the separator | as an argument. This will output the elements of the array as a
single string with pipe | characters separating each element: "Pen|Pencil|Eraser|Box"
It's important to note that the join() method does not modify the original array, it only
returns a new string.
In this example, the join function is used to concatenate all the elements of the array into
a single string, the first call to join will use the default separator (,) and the second call
will use the separator |. The output of both calls will be different and it will be useful in
different scenarios.
reverse()
The reverse() function in JavaScript is a method of the Array object, it is used to reverse
the order of the elements in an array. It modifies the original array in place, meaning that
it changes the order of the elements in the original array, and it doesn't return a new
array.
You can also use the reverse() method with an array of objects, but the order of the
elements will be based on their memory addresses rather than their properties. If you
need to sort an array of objects based on a specific property, you can use the sort()
function with a comparator function, which compares the values of the specified
property.
It's also important to note that, this method doesn't work on objects, it only works on
Arrays.
59
For example, the below code demonstrates the use of the reverse() method in
JavaScript.
The first part of the code creates an array called n which contains six elements: 1, 2, 3,
4, 5, and 6. The first console.log() statement outputs the original array to the console,
labeled as "Before Reverse".
The second line of the code calls the reverse() method on the n array, which changes
the order of the elements in the array. The elements are now in reverse order: 6, 5, 4, 3,
2, 1 The second console.log() statement outputs the reversed array to the console,
labeled as "After Reverse".
The second part of the code creates an object called x which has properties 0, 1, 2, 3
and a length property 4. The first console.log() statement outputs the object to the
console.
The next line of the code calls the reverse() method on the x object, but this will throw an
error because the reverse method is only available for Arrays. To overcome this issue,
the code uses the Array.prototype.reverse.call(x) method. This allows you to call the
reverse() method on the x object, and it changes the order of the properties of the
object. The second console.log() statement outputs the reversed object to the console.
It's important to note that, this way of reversing the properties of an object is not a
standard way and it's not a recommended one because it's not a good practice to modify
the Array's prototype, and it may cause unexpected behavior.
Source Code
const n = [1, 2, 3, 4, 5, 6];
console.log("Before Reverse : ", n);
n.reverse();
console.log("After Reverse : ", n);
Array.prototype.reverse.call(x);
console.log(x);
60
In summary, the reverse() method is useful to change the order of the elements in an
array, reversing the order of the elements in the original array and it doesn't return a new
array.
push()
The push() function in JavaScript is a method of the Array object, it is used to add one or
more elements to the end of an array. It modifies the original array in place, meaning
that it adds new elements to the end of the original array, and it doesn't return a new
array.
It's important to note that, the push() method modifies the original array, it doesn't return
a new array and you can use it to add elements to the end of an array regardless of its
size.
The first part of the code creates an array called n which contains 5 elements: 1, 2, 3, 4,
and 5. The first console.log() statement outputs the original array to the console.
The next line calls the push() method on the n array, passing the value 60 as an
argument. The element 60 is added to the end of the array, making the new array: [1, 2,
3, 4, 5, 60] The second console.log() statement outputs the value returned by the push
method, which is the new length of the array.
The next line calls the push() method on the n array again, passing multiple values 70,
85, 90, and 100 as arguments. These elements are added to the end of the array,
making the new array [1, 2, 3, 4, 5, 60, 70, 85, 90, 100] The third console.log() statement
outputs the array to the console.
The second part of the code creates an array called fruits which contains one element
"Apple" The first console.log() statement outputs the original array to the console.
61
The next line calls the push() method on the fruits array, passing the value "Orange" as
an argument. The element "Orange" is added to the end of the array, making the new
array: ["Apple", "Orange"] The second console.log() statement outputs the array to the
console.
The next line calls the push() method on the fruits array again, passing multiple values
"Banana" and "Pineapple" as arguments. These elements are added to the end of the
array, making the new array ["Apple", "Orange", "Banana", "Pineapple"] The third
console.log() statement outputs the array to the console.
The third part of the code creates two arrays called users1 and users2 which contains
["Ram", "Sam", "Ravi"] and ["Rajesh", "Kumar"] respectively. The next line uses the
spread operator (...) and calls the push() method on the users1 array, passing
the users2 array as an argument. This will merge the two arrays and add the elements
Source Code
let n = [1, 2, 3, 4, 5]
console.log(n);
console.log(n.push(60));
console.log(n);
console.log(n.push(70, 85, 90, 100));
console.log(n);
users1.push(...users2);
console.log(users1);
62
In summary, the push() method is useful to add one or more elements to the end of an
array, it increases the length of the array by the number of elements added, it modifies
the original array and it doesn't return a new array.
pop()
The pop() function in JavaScript is a method of the Array object, it is used to remove the
last element from an array and returns the removed element. It modifies the original
array in place, meaning that it removes the last element of the original array, and it
doesn't return a new array.
The code creates an array called users which contains four elements: 'Ram', 'Sam',
'Ravi' and 'Kumar'. The first console.log() statement outputs the original array to the
console.
The next line calls the pop() method on the users array, which removes the last element
from the array (in this case 'Kumar') and returns the removed element. The returned
element is logged to the console. The second console.log() statement outputs the
modified array to the console, which no longer contains the last element 'Kumar'.
The next line calls the pop() method on the users array again, which removes the last
element from the array (in this case 'Ravi') and returns the removed element. The
returned element is logged to the console. The third console.log() statement outputs the
modified array to the console, which no longer contains the last element 'Ravi'.
It's important to note that, the pop() method modifies the original array and it also
decreases the length of the array by 1. Each time the pop method is called, it removes
the last element of the array and returns it. If the array is empty and the pop method is
called, it returns undefined.
Source Code
//POP in JavaScript.
63
const users = ['Ram', 'Sam', 'Ravi', 'Kumar'];
console.log(users);
console.log(users.pop());
console.log(users);
console.log(users.pop());
console.log(users);
In summary, the code demonstrates the use of the pop() method to remove the last
element of an array and return it. The method modifies the original array, decreases the
length of the array by 1 and it doesn't return a new array.
shift()
The shift() function in JavaScript is a method of the Array object, is used to remove and
return the first element of an array. It modifies the original array and changes its length.
If the array is empty, undefined is returned.
The code defines an array named students which contains 6 elements: "Kumar",
"Aureen", "Joes", "Zara", "Stanley", and "Rajesh".
The first call to console.log() outputs the original array, "Before shift :
Kumar,Aureen,Joes,Zara,Stanley,Rajesh".
64
Then, the shift() function is called on the students array, which removes the first element
("Kumar") from the array and assigns it to the variable element.
The second call to console.log() outputs the modified array, "After shift :
Aureen,Joes,Zara,Stanley,Rajesh".
The third call to console.log() outputs the removed element, "Removed Element :
Kumar"
Then, again the shift() function is called on the modified array, which removes the first
element ("Aureen") from the array and assigns it to the variable element.
The fourth call to console.log() outputs the modified array after the second shift, "After
shift : Joes,Zara,Stanley,Rajesh".
The fifth call to console.log() outputs the removed element, "Removed Element :
Aureen"
The shift() function is used to remove the first element of an array and to return the
removed element. Each time the shift() function is called on the array, it will remove the
first element of the array and return that element, until all elements of the array are
removed.
unshift()
In JavaScript, the unshift() function is used to add one or more elements to the
beginning of an array and returns the new length of the array. It modifies the original
array by adding new elements to the beginning of the array.
//Mulitiple Values
65
len = students.unshift("Riya", "Diya");
console.log("Length : " + len);
console.log("After unshift : " + students);
This code demonstrates the usage of the unshift() function in JavaScript.
The code defines an array named students which contains 6 elements: "Kumar",
"Aureen", "Joes", "Zara", "Stanley", and "Rajesh".
The first call to console.log() outputs the original array, "Before unshift :
Kumar,Aureen,Joes,Zara,Stanley,Rajesh".
Then, the unshift() function is called on the students array with the argument "Tiya" ,
which adds the "Tiya" element to the beginning of the array and returns the new length
of the array which is assigned to variable len and then printed with the help of the
second call to console.log().
The third call to console.log() outputs the modified array, "After unshift :
Tiya,Kumar,Aureen,Joes,Zara,Stanley,Rajesh".
Then, again the unshift() function is called on the modified array with the arguments
"Riya" and "Diya", which add the "Riya" and "Diya" elements to the beginning of the
array and returns the new length of the array which is assigned to variable len and then
printed with the help of the fourth call to console.log().
The fifth call to console.log() outputs the modified array, "After unshift :
Riya,Diya,Tiya,Kumar,Aureen,Joes,Zara,Stanley,Rajesh".
The unshift() function is used to add one or more elements to the beginning of an array
and returns the new length of the array. Each time the unshift() function is called on the
array, it will add the new element(s) to the beginning of the array and return the new
length of the array, until all desired elements are added.
indexOf()
In JavaScript, the indexOf() function JavaScript is used to search an array for a specific
element and return the first index at which the element can be found. If the element is
not present in the array, it will return -1.
66
The syntax for the indexOf() function is as follows:
array.indexOf(element)
Here's an example of how it can be used:
Source Code
students = ["Tiya", "Aureen", "Joes", "Zara", "Stanley", "Rajesh"];
let i=students.indexOf("Tiya");
console.log("Index : "+i);
index=user.indexOf("o",5);
console.log("Index : "+index);
The code defines an array named students which contains 6 elements: "Tiya", "Aureen",
"Joes", "Zara", "Stanley", and "Rajesh".
The first line of code calls the indexOf() function on the students array with the argument
"Tiya", which searches the array for the first occurrence of "Tiya" and returns its index,
which is then assigned to the variable i and printed with the help of the first call
to console.log().
The second line of code defines a variable named user which is assigned the string
value "Tutor Joes".
The third line of code calls the indexOf() function on the user string with the argument
"o", which searches the string for the first occurrence of "o" and returns its index, which
is then assigned to the variable index and printed with the help of the second call
to console.log().
The fourth line of code calls the indexOf() function on the user string with the arguments
"o" and 5 which specifies that it should start searching for the "o" from index 5, and
returns its index, which is then assigned to the variable index and printed with the help of
the third call to console.log().
In the last console.log() statement, the third call to console.log() outputs the index of the
second o in the string which is 6.
67
It is important to note that the indexOf() method returns the first index at which the
element can be found. If the element is not present in the array or string, it will return -1.
lastIndexOf()
It is important to note that the lastIndexOf() method checks for strict equality (===)
between the elements
let i=students.indexOf("Tiya");
console.log(i);
i=students.lastIndexOf("Tiya");
console.log(i);
The code defines an array named students which contains 7 elements: "Tiya", "Aureen",
"Joes", "Zara", "Stanley", "Tiya", and "Rajesh".
The first line of code calls the indexOf() function on the students array with the argument
"Tiya", which searches the array for the first occurrence of "Tiya" and returns its index,
which is then assigned to the variable i and printed with the help of the first call
to console.log().
68
The second line of code calls the lastIndexOf() function on the students array with the
argument "Tiya", which searches the array for the last occurrence of "Tiya" and returns
its index, which is then assigned to the variable i and printed with the help of the second
call to console.log().
The third line of code defines a variable named address which is assigned the string
value "Tutor Joes Cherry Road Salem Joes".
The fourth line of code calls the indexOf() function on the address string with the
argument "Joes", which searches the string for the first occurrence
In JavaScript, the every() and some() functions are used to perform a test on all
elements of an array and return a Boolean value indicating whether all or some of the
elements pass the test, respectively.
The every() function takes a callback function as an argument, which is called for each
element in the array. The callback function is passed three arguments: the current
element, the index of the current element, and the array itself. If the callback function
returns true for every element in the array, the every() function returns true. If the
callback function returns false for any element in the array, the every() function returns
false.
The some() function also takes a callback function as an argument, and it also calls it for
each element in the array. If the callback function returns true for any element in the
array, the some() function returns true. If the callback function returns false
let result=n.every((value)=>{
return value%2==0;
});
result=n.some((value)=>{
return value%2==0;
});
69
function checkEven(value) {
return value % 2 == 0;
}
result=n.every(checkEven);
console.log("checkEven All Elements are Even :" ,result);
const users = [
{ name: "Ram", age: 25},
{ name: "Tiya", age: 45},
{ name: "Raja", age: 18},
{ name: "Sara", age: 12}
];
function isEligible(element) {
return element.age>=18;
}
result = users.every(isEligible);
console.log("Every Eligible :" , result);
result = users.some(isEligible);
console.log("Some Eligible :" , result);
This code demonstrates the usage of the every() and some() functions in JavaScript.
The code defines an array named n which contains 4 elements: 12, 18, 10, 8.
The first line of code calls the every() function on the n array and passed a callback
function that checks if each element is even by using the modulus operator. Since all
elements of the array are even, the every() function returns true.
The second line of code calls the some() function on the n array with the same callback
function, which checks if any element of the array is even. Since all elements of the
array are even, the some() function also returns true.
The third line of code defines a function named checkEven which takes a value and
checks if it is even. The every() function is called on the n array with checkEven function
passed as an argument. As the result it returns true.
The code then defines an array of objects named users which contains 4 objects, each
representing a user with properties name and age.
The isEligible function is defined which takes an element and checks if its age is greater
than or equal to 18.
70
The every() function is called on the users array with the isEligible function passed as an
argument. As it only Raja object is not eligible, it returns false
The some() function is called on the users array with the isEligible function passed as an
argument. As Ram and Tiya objects are eligible, it returns true
In JavaScript, there are two types of data types: primitive and reference.
Primitive data types are stored in the stack memory, and when a variable is assigned a
primitive value, it is assigned a copy of that value. This means that when you change the
value of a primitive variable, it does not affect any other variables that have the same
value.
Reference data types, on the other hand, are objects and arrays. They are stored in the
heap memory, and when a variable is assigned a reference value, it is assigned a
reference to the object or array in the heap. This means that when you change the value
of a reference variable, it will affect any other variables that reference the same object or
array.
In summary, Primitive data types are basic data types in JavaScript which are stored in
the stack memory, and when you change the value of a primitive variable, it does not
affect any other variables that have the same value. While Reference data types are
objects and arrays which are stored in the heap memory and when you change the
value of a reference variable, it will affect any other variables that reference the same
object or array.
Here are some examples of primitive and reference data types in JavaScript
71
Primitive data types
Example
Example
72
let user = {name: "Tutor Joes", age: 30}; // Object
let numbers = [1, 2, 3, 4, 5]; // Array
let today = new Date(); // Object
Here's an example of how primitive and reference data types behave differently when
assigned to multiple variables:
let x = 10;
let y = x;
x = 20;
console.log(x); // 20
console.log(y); // 10
In the first example, the value of x is changed to 20, but the value of y remains 10,
because x and y are primitive data types and they have different memory location.
In the second example, the value of user.age is changed to 25, and the value of
user2.age also changes to 25, because user and user2 are reference data types, and
they reference the same object in memory, so changing one of them will change the
other.
let arr1=[10,20,30];
let arr2=arr1;
console.log("Array 1 :",arr1);
console.log("Array 2 :",arr2);
arr1.push(40);
console.log("After Pushing element to arr1 : ");
console.log("Array 1 :",arr1);
console.log("Array 2 :",arr2);
73
In this code, the variable arr1 is assigned the value of an array, which is a reference
data type. The variable arr2 is then assigned the value of arr1. This means that arr2 is a
reference to the same array in memory as arr1.
When an element is pushed to arr1 using the push method, because both arr1 and arr2
are pointing to the same memory location, the change made to arr1 (i.e adding an
element) is also reflected in arr2.
This behavior is different from primitive data types, where if you change the value of one
variable, it does not affect the value of another variable that has the same value.
The Object.assign() method is used to copy the values of all enumerable own properties
from one or more source objects to a target object. It returns the target object. Here is an
example:
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const obj3 = Object.assign({}, obj1, obj2);
console.log(obj3); // { a: 1, b: 2, c: 3, d: 4 }
The spread operator (...) can also be used to create a shallow copy of an object. Here is
an example:
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const obj3 = {...obj1, ...obj2};
console.log(obj3); // { a: 1, b: 2, c: 3, d: 4 }
It should be noted that both Object.assign() and the spread operator create a shallow
copy, meaning that if the object being copied contains references to other objects, those
references will still be present in the copy and any changes made to the original object
will be reflected in the copy. If you want to create a deep copy, you can use a library
such as lodash.
In conclusion, the above code demonstrates the difference between primitive data types
and reference data types in JavaScript. Primitive data types are stored in memory as a
single value, while reference data types are stored as a reference or pointer to the
74
location in memory where the value is stored. This means that if two variables are
assigned a reference data type, they will both point to the same location in memory and
any changes made to one variable will also be reflected in the other variable.
Understanding this concept is important for proper memory management and avoiding
unexpected behavior in JavaScript.
There are multiple ways to create a clone of an array in JavaScript. Some of the most
common ways are:
Method-1
Using theSpread operator: The spread operator allows you to spread the elements of an
array into a new array. It creates a shallow copy of the array.
EXAMPLE
Method-2
Using theslice() method: The slice() method creates a shallow copy of the array. It takes
no arguments, it will create a copy of the entire array.
EXAMPLE
Method-3
Using theconcat() method: The concat() method creates a new array with the elements
of the original array and any additional elements that you pass to it.
EXAMPLE
75
let clonedArray = [].concat(originalArray);
console.log(clonedArray); // [1, 2, 3]
Method-4
Using theArray.from() method: The Array.from() method creates a new array with the
elements of the original array.
EXAMPLE
Method-5
It's important to note that all the above methods create a shallow copy of the array,
which means it will copy the elements of the original array but not the objects inside the
array.
76
Understanding the Use of const for Creating Arrays in
JavaScript
JavaScript offers several ways to declare variables, including var, let, and const. Each
keyword has its own unique behavior and use cases. In this blog post, we will focus on
the use of const for creating arrays in JavaScript.
When creating an array in JavaScript, you can use the const keyword to declare a
constant variable that refers to an array. For example:
const users=["Ram","Sam","Ravi"];
users.push("Tiya");
console.log(users);
The const keyword ensures that the variable users cannot be reassigned to a new value.
For example, you cannot do users = ["John", "Doe"]; which would throw an error.
However, the const keyword does not prevent modifications to the array elements
themselves. The array is an object in JavaScript, and the elements inside the array are
properties of that object. Therefore, you can still perform operations on the array
elements, such as pushing new elements to the array, changing the value of an element,
or using the splice method to remove elements.
In the code you've provided, the users.push("Tiya") method is used to add a new
element "Tiya" to the end of the array. This is a valid operation and the element is added
to the array. The console.log(users) statement then logs the updated array to the
console, which now has 4 elements ["Ram","Sam","Ravi","Tiya"].
Using the const keyword to declare an array in JavaScript has the following benefits:
• It prevents the variable from being reassigned to a new value. This can be useful
for maintaining the integrity of your data and ensuring that unexpected
reassignments do not occur in your code.
• It makes it clear to other developers that the array is meant to be constant and
should not be reassigned.
• It allows the elements inside the array to be modified. For example, you can still
push elements to an array, change the value of an element, or use the splice
method to remove elements even if the array is declared using const.
77
It's worth noting that, while the const keyword is generally recommended for arrays that
should not be reassigned, let keyword can also be used in situations where you want to
allow the array to be reassigned but still want to prevent modification to the elements
inside the array.
In summary, using const keyword to create an array is a good practice to ensure that the
array is not reassigned and it makes clear to other developers that this array is meant to
be a constant.
Array destructuring in JavaScript is a convenient way to extract values from arrays and
assign them to variables. The basic syntax for array destructuring is as follows:
let [variable1, variable2, ..., variableN] = array;
For example, if you have an array of numbers and you want to assign the first, second
and third elements to separate variables, you can use array destructuring like this:
In the above example, the first element of the numbers array is assigned to the
variable "a", the second element is assigned to the variable "b", and the third element is
assigned to the variable "c".
You can also use destructuring to extract elements from nested arrays. For example,
you can de-structure an array of arrays like this:
78
console.log(a); //1
console.log(b); //2
console.log(c); //3
console.log(d); //4
console.log(e); //5
console.log(f); //6
You can also use destructuring to extract elements from the end of an array like this:
In the above example ...c is called rest pattern, it will gather all the remaining element
into an array
In JavaScript, you can also use de-structuring to extract values from objects and assign
them to variables. The basic syntax for object de-structuring is as follows:
For example, if you have an object with properties "name", "age" and "gender" and you
want to assign the values of those properties to separate variables, you can use object
destructuring like this:
79
You can also use destructuring to extract values from nested objects. For example, you
can de-structure an object with nested objects like this:
let address = {street: "Cherry Road", city: "Salem", state: "Tamil Nadu", z
ip: "636007"};
let employee = {name: "Tiya", age: 12, gender: "female", address};
let {name, age, gender, address: {city, state, zip}} = employee;
console.log(name); // "Tiya"
console.log(age); // 30
console.log(gender); // "female"
console.log(city); // "Salem"
console.log(state); // "Tamil Nadu"
console.log(zip); // "636007"
You can also use destructuring to set default values for properties that might be missing
from the object. For example, you can destructure an object and set default values for
properties like this:
In the above example, if the person object does not contain the name,age and gender
properties, the destructuring will assign the default values to the variables.
80
Comparing Arrays and Objects in JavaScript:
Advantages and Disadvantages
In JavaScript, arrays and objects are both used to store collections of data, but they are
used in different ways.
Array
The items in an array are ordered, and each item is accessed by its position in the
array (also known as its index).
Arrays are commonly used to store lists of items, such as a list of numbers, a list of
names, or a list of objects.
Arrays are defined using square brackets, with items separated by commas.
EXAMPLE
Advantages
Arrays are used to store lists of items, which can be easily accessed, manipulated, and
iterated through using various array methods such as map, filter, and forEach. Arrays
are also efficient for searching and sorting large amounts of data. The position of an item
in an array (index) can be easily accessed which makes it easy to retrieve any data.
Disadvantages
Arrays are less efficient for storing large amounts of data when the keys are not
numbers. Retrieving a specific value in an array can be slower for large arrays since you
need to iterate through the array to find the value.
Objects
The keys in an object are used to access the values, and the keys and values can be of
any data type.
81
Objects are commonly used to store related data, such as a collection of properties for a
single item, or a collection of methods for an object.
Objects are defined using curly braces, with keys and values separated by colons.
EXAMPLE
Advantages
Objects are used to store key-value pairs of related data, which can be easily accessed,
manipulated, and iterated through using various object methods such
as for...in and Object.keys()
Objects are better suited for storing large amounts of data when the keys are strings,
because it is faster to retrieve values using keys than to iterate through an array.
Disadvantages
Objects are less efficient for searching and sorting large amounts of data because it
does not have any built-in methods to perform these operations.
The order of the keys in an object is not guaranteed, which can make it harder to work
with if the order is important.
In summary, arrays are used to store lists of items, while objects are used to store key-
value pairs of related data.
In conclusion, arrays and objects are both useful data structures in JavaScript, but they
have their own advantages and disadvantages. Arrays are great for storing lists of items
and are efficient for searching and sorting large amounts of data. On the other hand,
objects are better suited for storing key-value pairs of related data and are more efficient
for retrieving data using keys. Ultimately, the choice between using an array or an object
will depend on the specific needs of your project and the type of data you are working
with.
82
Creating Objects in JavaScript: A Detailed Guide
In JavaScript, objects are used to store collections of data and methods. There are
multiple ways to create objects in JavaScript, each with its own advantages and
disadvantages depending on the scenario.
This is the most common and simplest way to create an object. Object literals are
enclosed in curly braces {} and consist of a set of key-value pairs. Here is an example:
const person = {
name: "John",
age: 30,
job: "Developer"
};
console.log(person);
const personProto = {
sayHello: function() {
console.log(`Hello, my name is ${this.name}`);
}
};
83
const person = Object.create(personProto);
person.name = "John";
person.age = 30;
person.job = "Developer";
console.log(person);
In the above code snippet, we are creating an object called "personProto" that contains
a single method "sayHello()". This method takes advantage of the "this" keyword to
reference the "name" property of the object it is called on.
Next, we use the Object.create() method to create a new object called "person" that is
based on the "personProto" object. This is known as object prototypal inheritance.
We then add properties to the "person" object, such as "name", "age", and "job". These
properties are specific to this object and are not present on the "personProto" object.
Finally, we log the "person" object to the console, which will show all of its properties and
methods.
One of the advantages of using the Object.create() method is that it allows for efficient
object inheritance and property addition without the need for a constructor function and
the "new" keyword. Additionally, it allows for easy separation of methods and properties
shared among objects and those that are specific to an individual object.
4.USING CLASS:
class Person {
constructor(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
84
}
}
const person = new Person("Tiya", 30, "Developer");
console.log(person);
This code creates a class called "Person" using the class keyword. The class has a
constructor method which is called when a new object of the class is created using
the "new" keyword. The constructor takes 3 parameters: name, age, and job. Inside the
constructor method, the "this" keyword is used to create properties on the object being
created, and set their values to the values of the arguments passed to the constructor
method.
In this example, a new object of the class "Person" is created and assigned to the
variable "person". The values "Tiya", 30, and "Developer" are passed as arguments to
the constructor method. This causes the properties "name", "age" and "job" to be
created on the "person" object, and their values set to "Tiya", 30, and "Developer"
respectively.
At the end of the code, the "console.log(person)" is used to log the object to the console.
This will display the object with its properties and values.
Once an object is created, you can add properties and methods to it, and access them
using dot notation (person.name) or bracket notation (person["name"]).
Additionally, you can use destructuring to extract data from an object. Here is
an example:
In conclusion, the choice of creating an object will depend on the specific requirements
of your application. Each method has its own advantages and disadvantages and it's
important to understand them to make the best use of them.
85
In JavaScript, objects can be accessed using either dot notation or bracket notation.
Dot notation is used to access object properties using a dot followed by the property
name. For example, if an object has a property called "name", it can be accessed using
the following syntax:
object.name
Bracket notation is used to access object properties using the object name inside a set
of square brackets [] followed by the property name. For example, if an object has a
property called "name", it can also be accessed using the following syntax:
object["name"]
One key difference between the two is that dot notation can only be used to access
properties that have valid identifier names, while bracket notation can be used to access
properties using any string, including variables and expressions. Additionally, bracket
notation is useful when the property name is not known until runtime.
In general, dot notation is more readable and easier to understand, but bracket notation
can be more flexible.
Here is an example of using dot notation and bracket notation in JavaScript objects:
const user = {
name: "Tutor Joes",
age: 30,
job: "Developer"
};
// Dot notation
console.log(user.name); // Output: "Tutor Joes"
user.name = "Joes";
console.log(user.name); // Output: "Joes"
// Bracket notation
console.log(user["age"]); // Output: 30
user["age"] = 25;
console.log(user["age"]); // Output: 25
In the above example, we first create an object called "user" with properties "name",
"age", and "job". We then use dot notation to access the "name" property and change its
86
value to "Joes". We also use bracket notation to access the "age" property and change
its value to 25.
The main difference between dot notation and bracket notation in JavaScript object is
the way you access and modify the properties of the object.
Dot notation is used to access and modify the properties of an object using
the "." operator. For example, in the example above, we use user.name to access the
"name" property of the object and user.name = "Joes" to change the value of the "name"
property.
Bracket notation is used to access and modify the properties of an object using
the "[]" operator. For example, in the example above, we use user["age"] to access the
"age" property of the object and user["age"] = 25 to change the value of the "age"
property.
One of the main advantages of using bracket notation is that it allows you to access
properties using variables. For example, you can use a variable to store the property
name and then use that variable in the bracket notation to access the property.
Another advantage of using bracket notation is that it allows you to use property names
that are not valid JavaScript identifiers.
In contrast, dot notation can only be used with property names that are valid JavaScript
identifiers.
Both dot notation and bracket notation have their own advantages and disadvantages.
It's depended on your requirement and use case which one you want to use.
In JavaScript, keys in object cannot have spaces when using either dot notation or
bracket notation to access them. If a key has a space in it, you will need to use bracket
notation and put the key in quotes to access it. For example, if you have an object like
this:
let user = {
"first name": "Tutor",
87
"last name": "Joes"
};
You would use bracket notation to access the values like this:
If you try to use dot notation, it will not work and throw a syntax error, as the key
contains spaces.
You can use a variable to store the key and use it in bracket notation, like this:
In general, it's better to avoid keys with spaces in them, it's more readable and less
error-prone.
In conclusion, both dot notation and bracket notation are used to access properties of
JavaScript objects. However, they have some key differences. Dot notation is simpler
and easier to read, but it can only be used with valid identifiers, whereas bracket
notation allows the use of any string as a property name. Additionally, bracket notation
can be used to access properties using variables, whereas dot notation cannot.
Therefore, depending on your use case, one notation may be more suitable than the
other.
In JavaScript, objects can be iterated through using several methods, including the for-in
loop, Object.keys(), Object.values(),and Object.entries().
88
Example 1: Using the for-in loop
const user = {
name: "Tiya",
age: 30,
job: "Programmer"
};
Output
name: Tiya
age: 30
job: Programmer
Output
name: Tiya
age: 30
job: Programmer
89
Example 3: Using Object.values()
const user = {
name: "Tiya",
age: 30,
job: "Programmer"
};
Output
Tiya
30
Programmer
Output
name: Tiya
age: 30
job: Programmer
90
we can use many different ways to iterate through JavaScript objects using a for
loop.iterate through an object is using the Object.keys() method. This method returns an
array of the object's own property names. Here is an example:
const person = {
name: "Tiya",
age: 30,
job: "Programmer"
};
In this example, we are using the Object.keys() method to get an array of the object's
own property names. We can then use a traditional for loop to iterate through the array.
Output
name: Tiya
age: 30
job: Programmer
Lastly, we can use the Object.entries() method to iterate through an object. This method
returns an array of arrays, where each inner array is a key-value pair of the object's
properties. Here is an example:
const person = {
name: "Tiya",
age: 30,
job: "Programmer"
};
91
}
In this example, we are using the Object.entries() method to get an array of arrays,
where each inner array is a key-value pair of the object's properties. We can then use a
traditional for loop to iterate through the array.
Output
name: Tiya
age: 30
job: Programmer
In conclusion, there are several ways to iterate through JavaScript objects and each
method has its own use case. The for-in loop is useful when you need to access both
the keys and values of an object, Object.keys() and Object.values() are useful when you
only need to access the keys or values respectively, and Object.entries() is useful when
you need to access both the keys and values in an iterable format.
JavaScript objects are a powerful data structure that allows developers to store and
manipulate data in a flexible and organized manner. One of the most powerful features
of JavaScript objects is the ability to create properties with computed property names.
Computed property names allow developers to define the name of an object property at
runtime, rather than at the time of object creation. This means that the property name
can be determined based on the value of a variable or the result of an expression.
const key1="name";
const key2="age";
const value1="Joes";
92
const value2=35;
const user={
[key1]:value1,
[key2]:value2,
}
console.log(user);
In this example, we are using computed property names to create two properties in the
user object. The property names, "name" and "age", are determined by the values of the
variables key1 and key2, respectively. The values of these properties, "Joes" and 35,
are determined by the values of the variables value1 and value2, respectively.
When we run the code and log the user object to the console, we get the
following output:
As we can see, the properties of the user object have been created with the computed
property names, "name" and "age", and the values, "Joes" and 35, respectively.
Computed property names are a powerful feature of JavaScript objects that allow for
more dynamic and flexible code. They can be used to create properties with dynamic
names, extract values from objects, and improve code readability.
93
Unleashing the power of Spread operator in JavaScript
The spread operator (...) in JavaScript is used to spread the elements of an iterable
(such as an array or object) into a new array or object. It allows you to copy all of the
elements of an array or object into a new one without changing the original.
For example, you can use the spread operator to create a new array with all of the
elements of an existing array:
You can also use the spread operator to merge two arrays into a single array:
Similarly, you can use the spread operator to create a new object with all of the
properties of an existing object:
You can also use the spread operator to merge two objects into a single object
The spread operator can be used in many other ways to manipulate arrays and objects
in JavaScript.
94
In conclusion, the spread operator in JavaScript is a powerful tool that allows developers
to easily manipulate arrays and objects. It can be used for tasks such as merging arrays,
cloning objects, and transforming objects into arrays. The spread operator can also be
used in combination with other array and object methods to create more complex and
dynamic code.
As a developer, it's important to understand and utilize this feature to make your code
more efficient and readable.
Objects inside arrays are a common pattern in JavaScript, as arrays are often used to
store collections of similar data. For example, an array of user objects might look like
this:
const users = [
{ name: 'joes', age: 25, email: '[email protected]' },
{ name: 'ram', age: 32, email: '[email protected]' },
{ name: 'sam', age: 45, email: '[email protected]' }
];
This array contains three objects, each representing a user with properties such as
name, age, and email. This kind of data structure is commonly used in web development
to store and manipulate information about users, products, or other entities.
One common use case for objects inside arrays is to loop through the array and perform
some action on each object. For example, we might want to display the names of all
users on a website:
95
Output
joes
ram
sam
Another use case is to filter the array based on certain properties of the objects. For
example, we might want to find all users who are older than 30:
Output
[
{ name: 'ram', age: 32, email: '[email protected]' },
{ name: 'sam', age: 45, email: '[email protected]' }
]
Objects inside arrays in JavaScript can be used to store and organize related data in a
structured way. They can be used to store information about multiple items, such as a
list of products, users, or events.
• Reusability: You can easily reuse the same object structure for different data
• Flexibility: Using objects inside arrays allows you to store different types of data,
• Iteration: It allows for easy iteration using for loops or array methods such as
96
• Storing a list of products in an e-commerce application
You can use the array methods to iterate through the array and access each object and
its properties, or use destructuring and spread operator to manipulate the data
efficiently. Overall, using objects inside arrays in JavaScript can greatly enhance the
functionality and organization of your code. In Conclusion, Objects inside arrays are a
powerful pattern in JavaScript, enabling developers to store, manipulate and organize
data in a more efficient way.
JavaScript Functions:
What is Function?
In JavaScript, a function is a block of code that can be executed by calling it by its name,
and can optionally take in parameters and return a value. Functions are a fundamental
building block in JavaScript and are used to perform specific tasks or compute values.
They are often used to organize and structure code, making it more modular and
reusable. Functions can be declared in several ways in JavaScript, including function
declarations, function expressions, and arrow functions.
Function Declaration
function add(a, b) {
return a + b;
}
97
In this example, the function is named "add" and it takes in two parameters, "a" and "b".
The function's behavior is defined within the curly braces, where it simply returns the
sum of "a" and "b". This function can now be called by referencing its name, followed by
the arguments in parentheses, like so:
Function declarations are hoisted, which means that they are available for use
throughout the entire scope in which they are defined, even before they are executed.
This allows you to call a function before it is defined in your code.
Function with a return statement
A function with a return statement is a function that, when called, evaluates one or more
expressions and returns a value to the calling code. The return statement is used to
specify the value that the function should return.
For example
function add(a, b) {
return a + b;
}
console.log(add(1, 2)); // Output: 3
In this example, the function add takes two parameters a and b, and returns their sum
using the return statement. When the function is called with the arguments 1 and 2, it
returns the value 3 which is then logged to the console. Function with return statement
can be used to perform calculation, make decision and return the output as per the
requirement.
Function with Arbitrary arguments
function sum() {
let total = 0;
for (let i = 0; i<arguments.length; i++) {
98
total += arguments[i];
}
return total;
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(1, 2, 3, 4, 5)); // 15
Additionally, the spread operator (...) can also be used to accept an arbitrary number of
arguments. The spread operator allows the elements of an array to be spread out into
individual arguments. For example:
function sum(...args) {
let total = 0;
for (let i = 0; i<args.length; i++) {
total += args[i];
}
return total;
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(1, 2, 3, 4, 5)); // 15
For example, the following code defines a function and assigns it to a variable
named "add":
99
Arrow Function
An arrow function, also known as a "fat arrow" function, is a shorthand syntax for
defining a function in JavaScript. It was introduced in ECMAScript 6 (ES6) and is now a
widely used feature in JavaScript development.
For example
If the function body contains a single expression, you can also use the shorthand syntax,
omitting the curly braces and the "return" keyword:
Arrow functions have some important differences when compared to traditional function
expressions:
• The "this" keyword inside an arrow function refers to the same "this" as the
• Arrow functions do not have a "arguments" object, and you should use the rest
• Arrow functions are useful for creating concise, readable code and for passing
Here is the some more examples of using arrow functions in JavaScript with detailed
explanations:
100
1. Using arrow functions with map():
let numbers = [1, 2, 3, 4, 5];
let doubledNumbers = numbers.map(number => number * 2);
console.log(doubledNumbers); // [2, 4, 6, 8, 10]
In this example, the map() method is used to iterate over an array of numbers and
double each one. The arrow function number => number * 2 is passed as an argument
to the map() method and is invoked for each element in the array. The result is a new
array with the doubled numbers.
2. Using arrow functions with filter():
let words = ['apple', 'banana', 'orange', 'grape'];
let filteredWords = words.filter(word =>word.length> 5);
console.log(filteredWords); // ['banana', 'orange']
In this example, the filter() method is used to filter out elements in an array of words that
are shorter than 5 characters. The arrow function word =>word.length> 5 is passed as
an argument to the filter() method and is invoked for each element in the array. The
result is a new array containing only the words that are longer than 5 characters.
3. Using arrow functions with reduce():
let numbers = [1, 2, 3, 4, 5];
let total = numbers.reduce((sum, number) => sum + number, 0);
console.log(total); // 15
In this example, the reduce() method is used to iterate over an array of numbers and
add them together. The arrow function (sum, number) => sum + number is passed as
the first argument to the reduce() method and is invoked for each element in the array.
The second argument, 0, is the initial value of the accumulator (sum). The result is the
total sum of all the numbers in the array.
return () => {
101
count++;
return count;
};
};
let counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
In this example, the reduce() method is used to iterate over an array of numbers and
add them together. The arrow function (sum, number) => sum + number is passed as
the first argument to the reduce() method and is invoked for each element in the array.
The second argument, 0, is the initial value of the accumulator (sum). The result is the
total sum of all the numbers in the array.
These examples demonstrate how arrow functions can be used to write more concise
and readable code, particularly when working with arrays, functions, and closures.
function addition(a,b=5)
{
return a+b;
}
console.log(addition(25,30));
console.log(addition(25));
In the above code, the function "addition" has two parameters: "a" and "b". The
parameter "b" has a default value of 5, meaning that if the caller of the function does not
provide a value for "b", the value 5 will be used.
102
The first call to the function, "console.log(addition(25,30))", passes in two arguments: 25
for "a" and 30 for "b". The function returns the sum of these values (25 + 30 = 55), which
is then logged to the console.
Function hoisting is a feature in JavaScript that allows you to call a function before it is
defined in the code. This occurs because when JavaScript is interpreted, all function
declarations are moved to the top of their scope, which is known as hoisting.
function hoistedFunction() {
console.log("I'm a hoisted function");}
In this example, the function hoistedFunction is called before it is defined in the code.
However, it still executes successfully because the function declaration is hoisted to the
top of the scope, making it available to call throughout the entire scope.
It's important to note that function hoisting applies only to function declarations and not
function expressions.
notHoistedFunction(); // ReferenceError
let notHoistedFunction = function(){
console.log("I'm a function expression");
}
In this example, calling notHoistedFunction before the function expression is defined will
result in a ReferenceError
103
Function hoisting can be useful in certain situations but it can also lead to unexpected
behavior if not used correctly. It's good practice to always define functions before calling
them in your code to avoid confusion and bugs.
Nested Function
function outerFunction() {
let outerVariable = 'I am a variable in the outer function';
function innerFunction() {
let innerVariable = 'I am a variable in the inner function';
console.log(outerVariable); // Output: "I am a variable in the outer fu
nction"
console.log(innerVariable); // Output: "I am a variable in the inner fu
nction"
}
innerFunction();
}
outerFunction();
In this example, the outerFunction defines a variable called outerVariable and a nested
function called innerFunction. The innerFunction has access to the outerVariable and
can access and use it.
Nested functions can be useful for creating more modular and organized code. They can
also be used to create closures, which are functions that maintain their state even after
they have returned.
It's important to note that inner functions have access to the variables and functions in
the parent function, but the parent function doesn't have access to the variables and
functions inside the inner function.
Also, the inner function can be invoked only by the parent function.
Lexical scope in JavaScript function
104
In JavaScript, lexical scope refers to the way in which the variables, functions, and
objects in a program are associated with specific scopes, or regions of the code where
they are accessible. Each function in JavaScript has its own scope, which is determined
by the location of the function in the code, and the scopes of any parent functions that
contain it.
function innerFunction() {
let innerVariable = 'I am a variable in the inner function';
console.log(globalVariable); // Output: "I am a global variable"
console.log(outerVariable); // Output: "I am a variable in the oute
r function"
console.log(innerVariable); // Output: "I am a variable in the inne
r function"
}
innerFunction();
}
outerFunction();
JavaScript has a lexical scoping which means that the scope of a variable is defined by
its location in the code, and not by its execution context.Understanding lexical scope is
an important part of understanding how JavaScript works and can help you write more
efficient and effective code.
Block scope refers to variables declared within a block using the let or const keyword.
These variables are only accessible within that block and any nested blocks. A block is
defined as any section of code enclosed by curly braces {}.
For example
if (true) {
let blockScopeVariable = 'I am a variable with block scope';
console.log(blockScopeVariable); // Output: "I am a variable with block s
cope"
}
console.log(blockScopeVariable); // ReferenceError: blockScopeVariable is n
ot defined
Function scope refers to variables declared within a function using the var keyword (or
no keyword at all). These variables are only accessible within that function and any
nested functions.
For example
function myFunction() {
var functionScopeVariable = 'I am a variable with function scope';
console.log(functionScopeVariable); // Output: "I am a variable with func
tion scope"
}
console.log(functionScopeVariable); // ReferenceError: functionScopeVariabl
e is not defined
It's important to note that block scope is introduced with let and const in ECMAScript 6
(ES6)and it's now the preferred way for declaring variables in javascript.
106
Here's an example to demonstrate the difference between block scope and function
scope in JavaScript:
function myFunction() {
if(true){
let fullname="Joes";
console.log(fullname);
}
console.log(fullname);
}
myFunction()
In this example, the variable fullname is defined as a block scope variable and is only
accessible within the block it is declared in. When the console.log(fullname) statement is
executed inside the if block, it correctly outputs "Joes". However, when the
console.log(fullname) statement is executed outside of the if block, it raises a
ReferenceError, because the variable fullname is not defined in that scope.
function myFunction() {
if(true){
var fullname="Joes";
console.log(fullname);
}
console.log(fullname);
}
myFunction()
In this example, the variable fullname is defined as a function scope variable and is
accessible within the entire function. When the console.log(fullname) statement is
executed inside the if block, it correctly outputs "Joes". When
the console.log(fullname) statement is executed outside of the if block, it correctly
outputs "Joes" too, because the variable fullname is defined in the function scope.
Using the appropriate scope for your variables can help prevent naming conflicts,
improve the readability of your code, and make it easier to debug issues. As a general
rule of thumb, use let and const for block scope variables and avoid using varas it can
lead to unexpected behavior.
107
In conclusion, understanding the difference between block scope and function scope in
JavaScript is crucial to writing maintainable and efficient code.
Block scope variables, declared with the let or const keyword, are only accessible within
the block they are defined in and any nested blocks. Function scope variables, declared
with the var keyword, are only accessible within the function they are defined in and any
nested functions. It is recommended to use block scope variables (let, const) instead of
function scope variables (var) as it can prevent naming conflicts and improve the
readability of the code.
JavaScript is a powerful programming language that provides many features and tools to
make coding easier and more efficient. Two of these features are the rest parameter
function and the spread operator, which are similar in that they both handle multiple
arguments, but have different uses and syntax.
In this example, the function "myFunction" takes three arguments: "first", "second", and
"rest". "rest" is a rest parameter, and it will collect all the remaining arguments into an
array.
108
On the other hand, the spread operator is used to expand an iterable (such as an array
or string) into individual elements. The spread operator is defined by three dots (...) and
can be used in function calls, array literals, and object literals. For example:
In this example, the spread operator is used to expand the elements of "myArray" into a
new array "newArray".
In summary, the rest parameter function and the spread operator are both useful tools in
JavaScript for handling multiple arguments, but they have different uses and syntax. The
rest parameter function is used to gather remaining arguments into an array, while the
spread operator is used to spread elements of an array or iterable. Understanding the
differences between these two features can help you write cleaner, more efficient code.
Instead of accessing the properties of this object using dot notation or bracket notation,
we can destructure the object's properties directly into variables. Here's an example of a
109
function that takes a single argument, an object, and destructures its name property to
say hello:
We can also set default values for properties when destructuring if the property is not
present in the object.
We can also use the rest operator to collect remaining properties in a single variable.
const person = {name: 'Joes', age: 30, city: 'Salem', country: 'India'};
110
sayHello(person); // Output: "Hello, Joes! You are 30 years old" and {city:
'Salem', country: 'India'}
JavaScript is a versatile and powerful programming language that offers many ways to
structure and organize code. One such technique is the use of callback functions. In this
blog post, we will explore what callback functions are, how they are used, and some
common use cases.
function higherOrderFunction(callback) {
// some code
callback();
// some code
}
The callback function can then be passed as an argument when the higher-order
function is called:
function myCallback() {
console.log("I am a callback function");
}
higherOrderFunction(myCallback);
111
// Output: "I am a callback function"
One of the main use cases for callback functions is event handling. For example, you
can pass a callback function as an argument to an event listener, allowing for specific
actions to be taken when a specific event occurs, such as a button click or form
submission.
Another common use case is for asynchronous operations. Callback functions can be
passed as arguments to asynchronous functions, such
as setTimeout() or XMLHttpRequest, allowing for specific actions to be taken once the
asynchronous operation is complete.
setTimeout(function() {
console.log('Hello, world!');
}, 1000); // Output: "Hello, world!" after 1 second
Lastly, callback functions can also be used for partial application, allowing
to "fix" or "partial apply" some of the arguments of a function, creating a new function
with less arguments.
112
In conclusion, callback functions are a powerful tool in JavaScript that allows for greater
flexibility and reusability of code. By understanding how to use callback functions, you
can write more modular, reusable, and maintainable code.
A closure is a function that has access to the variables in the scope in which it was
defined, even after that scope has closed. This can be achieved by returning a function
that closes over the variables in its scope.
function outerFunction(x) {
return function innerFunction(y) {
return x + y;
}
}
We can also save the returned inner function to a variable and call it with different
arguments. This is useful in many cases like creating a set of utility functions that have
some shared state or configuration.
113
Here is an example of a closure function:
function createCounter() {
let count = 0;
return function() {
return count++;
}
}
const counter = createCounter();
console.log(counter()); // 0
console.log(counter()); // 1
console.log(counter()); // 2
In this example, the createCounter function returns an inner function that closes over the
variable count. Every time the inner function is called, it returns the current value of
count, and then increments it by 1.
Closures are also commonly used in JavaScript libraries and frameworks for creating
specific behavior and functionality, such as creating private variables and methods in
objects and classes. Closures can also be used to create functional programming
patterns, such as currying and partial application.
In conclusion, closure functions, also known as inner functions, are a powerful tool in
JavaScript that allow for greater flexibility and reusability of code. By understanding how
to use closure functions, developers can create utility functions, encapsulation and also
write more elegant and efficient code.
114
Exploring the forEach method in JavaScript: More
Examples
The forEach method in JavaScript is a powerful tool for iterating over arrays. It allows
you to apply a callback function to each element in an array, making it a great option for
performing actions such as filtering, printing, or manipulating elements. In this blog post,
we'll take a look at ten practical examples of using the forEach method to work with
arrays in JavaScript.
In this example, the forEach method is used to iterate over the fruits array and print each
element. The callback function takes the current element as an argument, and simply
logs it to the console.
In this example, the forEach method is used to iterate over the numbers array and sum
all the elements. The callback function takes the current element and adds it to the total
variable, which is initially set to 0.
3. Example of using the forEach method to create a new array from an existing one:
115
});
console.log(doubledNumbers); // [2, 4, 6, 8, 10]
In this example, the forEach method is used to iterate over the numbers array and create a new array
containing the double of each element. The callback function takes the current element, multiplies it
by 2 and then pushes it to the new array.
4. Example of using the forEach method to find the max element of an array:
In this example, the forEach method is used to iterate over the numbers array and find the max
element. The callback function takes the current element and compares it with the max variable. If the
current element is greater than max, it updates the max variable.
In this example, the forEach method is used to iterate over the numbers array and
calculate the average. The callback function takes the current element and adds it to the
total variable, and increments the count variable. After the loop, the total and count
variables are used to calculate the average.
116
if (number % 2 === 0) {
evenNumbers.push(number);
}
});
console.log(evenNumbers); // [2, 4, 6, 8, 10]
In this example, the forEach method is used to iterate over the numbers array and filter
out the even numbers. The callback function takes the current element, checks if it is
divisible by 2 and if it is, it pushes the element to the evenNumbers array.
In this example, the forEach method is used to iterate over the names array and update
each element to uppercase. The callback function takes the current element and its
index, and updates the element at that index position to uppercase.
In this example, the forEach method is used to iterate over the numbers array and
remove elements greater than 5. The callback function takes the current element and its
index, and checks if the element is greater than 5, if it is it uses the splice method to
remove that element from the array.
117
const fruits = ['apple', 'banana', 'cherry'];
let exists = false;
fruits.forEach(fruit => {
if (fruit === 'banana') {
exists = true;
}
});
console.log(exists); // true
In this example, the forEach method is used to iterate over the fruits array and check if
the element 'banana' exists in the array. The callback function takes the current element
and compares it with 'banana', if they are equal it sets the exists variable to true.
10. Example of using the forEach method to check concat array element:
In this example, we have an array of words and we are using the forEach method to
iterate through the array and concatenate each word to a variable called "concat". Once
the forEach loop is completed, we log the value of "concat" to the console and it should
print "hello world ", which is the concatenation of all words in the array.
In conclusion, the forEach method is a powerful tool in JavaScript for iterating through
an array and performing a specific action on each element. It is a more concise and
readable way of performing operations on arrays compared to traditional for and while
loops. The forEach method does not return a new array and does not stop when it
encounters a return statement or throws an error, unlike other looping methods.
However, it can be used in conjunction with other array methods such as map, filter, and
reduce to perform more complex operations on arrays. It's a very useful method to have
in your tool belt as a JavaScript developer, and it's important to be familiar with its syntax
and usage.
118
Unleashing the Power of the filter() Method in
JavaScript: A Comprehensive Guide
The filter() method in JavaScript is a built-in method of the Array object that allows you to
create a new array with all elements that pass a certain test. The test is implemented by
a callback function that you provide as an argument to the filter() method. The callback
function is called for each element of the original array, and if it returns true, the element
is included in the new array. If it returns false, the element is excluded from the new
array.
A closure is a function that has access to the variables in the scope in which it was
defined, even after that scope has closed. This can be achieved by returning a function
that closes over the variables in its scope.
119
2. Filtering an array of objects to only include those with a certain property value:
let user = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 }
];
let eligible = people.filter(person =>person.age> 30);
console.log(eligible); // [{ name: 'Charlie', age: 35 }]
let items = [
{ name: "apple", category: "fruit" },
{ name: "carrot", category: "vegetable" },
{ name: "banana", category: "fruit" }
];
let fruits = items.filter(item =>item.category === "fruit");
console.log(fruits);
// [{ name: "apple", category: "fruit" }, { name: "banana", category: "frui
t" }]
6. Filtering an array of strings to only include those that start with a specific letter:
120
console.log(wordsStartsWithE); // ['elephant']
7. Filtering an array of objects to only include those with a certain property value:
let products = [
{ name: 'apple', price: 1.2 },
{ name: 'orange', price: 2.5 },
{ name: 'banana', price: 3.5 }
];
let expensiveProducts = products.filter(product =>product.price> 2);
console.log(expensiveProducts);
// [{ name: 'orange', price: 2.5 },{ name: 'banana', price: 3.5 }]
let buttons = [
{ name: 'Save', enabled: true },
{ name: 'Delete', enabled:false },
{ name: 'Cancel', enabled: true },
{ name: 'Submit', enabled: false }
];
let enabledButtons = buttons.filter(button =>button.enabled === true);
console.log(enabledButtons);
// [{ name: 'Save', enabled: true }, { name: 'Cancel', enabled: true }]
9. Filtering an array of numbers to only include those greater than a certain value:
10. Filtering an array of strings to only include those that contain a specific
substring:
121
11. Filtering an array of objects based on multiple conditions: Category Fruit and
Price > 100
const products = [
{ name: 'Apple', category: 'fruit', price: 100 },
{ name: 'Carrot', category: 'vegetable', price: 50 },
{ name: 'Orange', category: 'fruit', price: 120 },
{ name: 'Broccoli', category: 'vegetable', price: 75 },
{ name: 'Mango', category: 'fruit', price: 110 }
];
let books=[
{ title: 'Eloquent JavaScript', author: 'Marijn Haverbeke', year: 2011
},
{ title: 'JavaScript: The Good Parts', author: 'Douglas Crockford', yea
r: 2008 },
{ title: 'Learning Web Design: A Beginner\'s Guide to HTML, CSS, JavaSc
ript, and Web Graphics', author: 'Jennifer Niederst Robbins', year: 2012 },
{ title: 'HTML and CSS: Design and Build Websites', author: 'Jon Ducket
t', year: 2011 },
{ title: 'CSS Secrets: Better Solutions to Everyday Web Design Problems
', author: 'Lea Verou', year: 2015 },
{ title: 'JavaScript and JQuery: Interactive Front-End Web Development'
, author: 'Jon Duckett', year: 2014 },
{ title: 'You Don\'t Know JS', author: 'Kyle Simpson', year: '2014-2019
' },
{ title: 'React: Up & Running', author: 'Stoyan Stefanov', year: 2016 }
,
{ title: 'Node.js Design Patterns', author: 'Mario Casciaro', year: 201
4 },
{ title: 'Head First Design Patterns', author: 'Eric Freeman and Elisab
eth Robson', year: 2004 }
];
In addition, filter() always returns a new array and does not modify the original array. It
does not change the length of the original array and does not change the index of the
elements.
122
Conclusion
The filter() method is a powerful tool for manipulating arrays in JavaScript. With a little bit
of creativity, you can use it to solve a wide variety of problems. The examples in this
blog post should give you a good starting point for using the filter() method in your own
code.
Remember to always check the documentation and play around with different examples
to get a better understanding of how it works. With practice, you'll be able to filter arrays
like a pro!
JavaScript provides several ways to manipulate and transform arrays, but one of the
most popular and widely used methods is map.The map() method is used to create a
new array with the results of calling a provided function on every element in the calling
array. The map() method does not modify the original array, but instead, it creates a new
array with the modified elements. The function passed to map() is called for each
element in the array, and it takes three arguments: the current value, the current index,
and the entire array. The map() method is commonly used to transform an array of data
into a new format, such as converting an array of numbers into an array of strings.
In this article, we'll take a closer look at map and provide 10 examples to help you
master this powerful method.
1.Simple Transformation
In this example, we're using map to iterate through an array of numbers and double
each one. The resulting array, "doubledNumbers" contains the transformed values.
123
2.Given an array of numbers, write a function that returns a new array containing
only the even numbers from the original array, squared.
Example Input:
Solution:
function getEvenSquaredNumbers(numbers) {
const evenNumbers = numbers.filter(num => num % 2 === 0);
const squaredNumbers = evenNumbers.map(num => num ** 2);
return squaredNumbers;
}
In this example, we're using map to iterate through an array of words and capitalizing
each one. The resulting array, "capitalizedWords", contains the transformed values.
4.Given an array of objects representing books, create a new array containing the
book titles and authors in the format "Title by Author".
Example Input:
const books = [
{
title: 'The Great Gatsby',
author: 'F. Scott Fitzgerald'
},
{
title: 'To Kill a Mockingbird',
author: 'Harper Lee'
124
},
{
title: 'Pride and Prejudice',
author: 'Jane Austen'
}
];
Solution:
const bookTitlesAndAuthors = books.map(book => `${book.title} by ${book.aut
hor}`);
console.log(bookTitlesAndAuthors);
// Output:
// [
// "The Great Gatsby by F. Scott Fitzgerald",
// "To Kill a Mockingbird by Harper Lee",
// "Pride and Prejudice by Jane Austen"
// ]
Solution:
const fahrenheitTemperatures = celsiusTemperatures.map(temp => (temp * 9/5)
+ 32);
console.log(fahrenheitTemperatures);
// Output: [77, 86, 59, 50]
6. Combining Arrays
In this example, we're using map to combine elements from two different
arrays, "fruits" and "colors", into a new array "fruitColors".
125
7. Creating a new Array
In this example, we're using map to create a new array of the squared values
of numbers.
8. Filtering an Array
In this example, we're using map to filter an array, so that only even numbers remain.
const users = [
{ name: "Ram", age: 30 },
{ name: "Sam", age: 25 },
{ name: "Ravi", age: 35 }
];
const names = users.map(user => user.name);
console.log(names); // ["Ram", "Sam", "Ravi"]
In this example, we're using map to extract the "name" property from an array of objects.
const users = [
{ name: "Ram", age: 30 },
{ name: "Sam", age: 25 },
{ name: "Ravi", age: 35 }
];
const updatedUsers = users.map(user => {
return {
...user,
126
age: user.age + 1
}
});
console.log(updatedUsers);
// [{ name: "Ram", age: 31 }, { name: "Sam", age: 26 }, { name: "Ravi", age
: 36 }]
In this example, we're using map to iterate through an array of objects and increase
the "age" property by one. The resulting array "updatedUsers" contains the transformed
objects.
11. Given an array of strings, create a new array with the lengths of each string.
Example Input:
Solution:
const stringLengths = strings.map(str => str.length);
console.log(stringLengths);
// Output: [5, 5, 10]
12. Given an array of objects representing students, create a new array with their
full names.
Example Input:
const students = [
{ firstName: 'John', lastName: 'Doe' },
{ firstName: 'Jane', lastName: 'Smith' },
{ firstName: 'Mike', lastName: 'Johnson' }
];
Solution:
127
13. Flattening an Array
In this example, we're using map to flatten an array of nested arrays. The resulting
array "flattenedArray" contains the transformed values.
const dates = [
new Date("2022-01-01"),
new Date("2022-02-01"),
new Date("2022-03-01")
];
const formattedDates = dates.map(date =>date.toLocaleDateString());
console.log(formattedDates); // ["1/1/2022", "2/1/2022", "3/1/2022"]
In this example, we're using map to iterate through an array of date objects and format
them using the toLocaleDateString() method. The resulting
array "formattedDates" contains the transformed values.
128
console.log(nameElements);
In this example, we're using map to create an array of DOM elements using
the createElement() method. The resulting array "nameElements" contains the
transformed elements.
16. Suppose you have an array of objects representing different currencies with
their exchange rates to USD. You want to convert an amount from one currency to
another using the exchange rates.
Example Input:
const currencies = [
{ currency: 'USD', rate: 1 },
{ currency: 'EUR', rate: 0.85 },
{ currency: 'GBP', rate: 0.73 },
{ currency: 'JPY', rate: 109.97 }
];
const amount = 100; // Amount in USD
const targetCurrency = 'EUR';
Solution:
17. Formatting Phone Numbers - Suppose you have an array of phone numbers
represented as strings, and you want to format them in a specific pattern.(Slice
Function)
129
Example Input:
Solution:
console.log(formattedNumbers);
// Output: ["(123) 456-7890", "(987) 654-3210", "(555) 123-4567"]
18. Filtering and Mapping Data - Suppose you have an array of objects
representing products, and you want to filter out products with a certain condition
and create a new array with specific properties.
Example Input:
const products = [
{ id: 1, name: 'iPhone', price: 999, category: 'Electronics' },
{ id: 2, name: 'Shirt', price: 25, category: 'Fashion' },
{ id: 3, name: 'Book', price: 15, category: 'Books' },
{ id: 4, name: 'TV', price: 799, category: 'Electronics' },
];
Solution:
const filteredProducts = products
.filter(product => product.category === 'Electronics' && product.price >
500)
.map(product => ({ id: product.id, name: product.name }));
console.log(filteredProducts);
// Output: [
// { id: 1, name: 'iPhone' },
// { id: 4, name: 'TV' }
// ]
130
19. Fetching Data from an API - Suppose you are fetching data from an API that
returns an array of objects, and you want to extract specific information from each
object.
Example Input:
Solution:
const users = response.map(user => ({
id: user.id,
name: user.name,
email: user.email
}));
console.log(users);
// Output: [
// { id: 1, name: 'John Doe', email: '[email protected]' },
// { id: 2, name: 'Jane Smith', email: '[email protected]' },
// { id: 3, name: 'Mike Johnson', email: '[email protected]' }
// ]
20. Calculating Item Totals - Suppose you have an array of objects representing
items in a shopping cart, and you want to calculate the total price for each item by
multiplying the quantity and price.
Example Input:
const cartItems = [
131
{ name: 'Shirt', price: 20, quantity: 2 },
{ name: 'Pants', price: 30, quantity: 1 },
{ name: 'Shoes', price: 50, quantity: 1 }
];
Solution:
const itemTotals = cartItems.map(item => ({
name: item.name,
total: item.price * item.quantity
}));
console.log(itemTotals);
// Output: [
// { name: 'Shirt', total: 40 },
// { name: 'Pants', total: 30 },
// { name: 'Shoes', total: 50 }
// ]
Conclusion
The map() method in JavaScript is a powerful and versatile tool for working with arrays.
It allows you to easily transform and manipulate the elements of an array without
modifying the original data. The map() method is a great choice when you need to
create a new array with modified elements, such as converting an array of numbers into
an array of strings or extracting specific information from an array of objects.
Additionally, the map() method is also useful when you want to perform the same
operation on each element of an array, such as incrementing every number in an array
by 1. With the map() method, you can easily and efficiently work with arrays in
JavaScript.
The reduce() method in JavaScript is a powerful array method that allows you to iterate
through an array and reduce it to a single value. This method can be used for a variety
132
of tasks such as summing the values of an array, flattening an array, or counting the
occurrences of an element.
with the initialValue (if provided) or the first element of the array (if no initialValue
is provided)
• currentIndex : is the index of the current element of the array that is being
processed.
provided, the first element of the array is used as the starting value.
The reduce() method returns a single value that is the result of executing the callback
function on each element of the array.
133
In this example, we use the reduce() method to sum the values of an array of numbers.
The accumulator starts at the first element of the array and the currentValue is the next
element. We use the accumulator to store the sum and add the currentValue to it on
each iteration.
In this example, we use the reduce() method to flatten an array of arrays. We use
the concat() method to merge the currentValue (which is an array) into the accumulator
which is also an array).
}, {});
console.log(colorCounts); // { red: 2, blue: 2, green: 1, yellow: 1 }
In this example, we use the reduce() method to count the occurrences of each element
in an array. We use an object as the accumulator and check if the currentValue already
exists in the object. If it does, we increment the value by 1. If it doesn't, we add
the currentValue as a key to the object and set its value to 1.
134
});
console.log(largest); // 25
In this example, we use the reduce() method to find the largest value in an array of
numbers. We use the Math.max() method to compare the accumulator and the
currentValue on each iteration and return the larger value. The final value returned by
the reduce() method is the largest value in the array.
let people = [
{ name: 'Rakesh', age: 25, city: 'Chennai' },
{ name: 'Raj', age: 30, city: 'Salem' },
{ name: 'Sara', age: 35, city: 'Chennai' }
];
console.log(groupedByCity);
/*
{
Chennai: [{ name: 'Rakesh', age: 25, city: 'Chennai' }, { name: 'Sara', age
: 35, city: 'Chennai' }],
Salem: [{ name: 'Raj', age: 30, city: 'Salem' }]
}
*/
Conclusion
The reduce() method in JavaScript is a powerful tool for working with arrays. It allows for
the iteration and calculation of values within an array, making it easy to perform tasks
135
such as summing or finding the product of all elements in an array. The reduce() method
takes a callback function as an argument, which is used to specify the calculation to be
performed on each element of the array. The callback function takes two arguments:
an accumulator and the current value. The accumulator is used to store the result of the
calculation as the function iterates through the array. The initial value for the
accumulator can be provided or it takes the first element of the array as the starting
value. Overall, the reduce() method is a useful and versatile tool for working with arrays
in JavaScript.
const user={
firstName:"Tutor",
lastName:"Joes",
address:{
street:"Cherry Road",
city:"salem",
contact:"9043017689",
}
}
console.log(user?.firstName);
console.log(user?.address?.contact);
In the given example, user is an object that has several properties, including firstName,
lastName, and address. The two console.log statements are using the optional chaining
operator (?.) to access the properties of the user object without having to check if they
exist first.
136
The first console.log statement uses the optional chaining operator to access the
firstName property of the user object. Since the firstName property exists, the statement
will print the value of the property, which is "Tutor".
console.log(user?.firstName); // "Tutor"
The second console.log statement uses the optional chaining operator to access the
contact property of the address object, which is a nested object inside the user object.
Since the address and contact properties exist, the statement will print the value of the
property, which is "9043017689".
console.log(user?.address?.contact); // "9043017689"
The optional chaining operator allows you to check if the objects and its properties exist
without having to check them explicitly, which can make the code more concise and
readable. If any of the properties or objects in the chain don't exist, the expression will
return undefined instead of throwing a TypeError.
It's important to note that the optional chaining only applies to the part of the expression
immediately to the right of the ?. operator, so if a property is accessed with the optional
chaining operator and that property itself is undefined, the expression will still throw
a TypeError.
In JavaScript, functions can be defined inside objects, just like any other property. These
functions are called "methods" and can be invoked by using the object's name, followed
by the method name and parentheses.
137
For example:
const object = {
method: function() {
console.log("Hello, I'm a method!");
}
};
You can also define methods using the shorthand notation, which uses
the function keyword.
const object = {
method() {
console.log("Hello, I'm a method!");
}
};
You can also define methods using the arrow function notation, which is similar to the
shorthand notation but uses the => instead of function keyword
const object = {
method: () => {
console.log("Hello, I'm a method!");
}
};
Inside the method, you can access the properties of the object using the this keyword.
const object = {
property: "I'm a property",
method: function() {
console.log(this.property);
}
138
};
Methods can also accept parameters and return values just like regular functions:
const object = {
method: function(a, b) {
return a + b;
}
};
You can also add methods to an object after it has been created by assigning a new
method to an existing property, or by creating a new property on the object and
assigning a method to it.
In javascript you can use class keyword to create objects with methods and properties, it
follows the OOP concepts.
class Object {
constructor(){
this.property = "I'm a property";
}
method(){
console.log("Hello, I'm a method!");
}
}
const obj = new Object();
console.log(obj.property);
obj.method();
function checkEligiblity(){
if(this.age>=18){
139
console.log(`${this.firstname} age is ${this.age} eligible for vote
`);
}else{
console.log(`${this.firstname} age is ${this.age} not eligible for
vote`);
}
}
const user1={
firstname:"Joes",
age:35,
eligiblity:checkEligiblity
}
user1.eligiblity();
const user2={
firstname:"Sara",
age:12,
eligiblity:checkEligiblity
}
user2.eligiblity();
In JavaScript, it is common to define functions separately and then assign them to object
properties as methods. In the above example, the function checkEligibility is defined
separately and then assigned to the eligibility property of the user1 and user2 objects.
This allows the function to be reused as a method for multiple objects.
When the method is invoked on the user1 object, this inside the method will refer to
user1 object and when it is invoked on the user2 object, this inside the method will refer
to user2 object, This way checkEligibility function can use the properties of the current
object on which it is invoked.
140
Similarly, when user2.eligibility() is invoked, it will execute the checkEligibility function.
Inside the function, it uses the this keyword to access the properties of the user2 object,
namely firstname and age. The function then checks if the person's age is greater than
or equal to 18, and if not, logs a message saying that the person is not eligible to vote.
In this way, the function checkEligibility is used as a method for different objects and it
uses the this keyword to access the properties of the object that invokes it, making the
function more reusable.
In JavaScript, the call, apply, and bind methods are used to change the this context of a
function.
The call method is used to invoke a function and specify the this context. It takes an
object as its first argument, which becomes the this context for the function, followed by
any additional arguments for the function.
For example:
function total(eng,mat) {
console.log(this.name+" got "+(eng+mat)+" Marks");
}
The apply method is similar to call, but it takes an array of arguments for the function,
instead of a list of arguments.
For example:
function total(eng,mat) {
console.log(this.name+" got "+(eng+mat)+" Marks");
}
141
total.apply(user, [65,75]); // Ram got 140 Marks
The bind method is used to create a new function with the this context set to the
provided object. It takes an object as its first argument, which becomes the this context
for the new function, and any additional arguments for the function are passed as
arguments to the new function.
For example:
function total(eng,mat) {
console.log(this.name+" got "+(eng+mat)+" Marks");
}
In this way, call, apply and bind methods are used to change the this context of a
function, which allows for greater flexibility and reusability of code.
In conclusion, understanding and mastering the use of the call, apply, and bind methods
in JavaScript is an important aspect of object-oriented programming. These methods
allow you to change the this context of a function, enabling greater flexibility and
reusability of code. With the ability to invoke a function with a specific context, pass an
array of arguments, and create a new function with a pre-defined context, you will be
able to write more efficient and maintainable code. Understanding these methods is
essential for any JavaScript developer who wants to take their skills to the next level.
JavaScript is a powerful and versatile language, with a lot of features and concepts to
master. One of the most important concepts to understand is the this keyword. In this
blog post, we will dive into how the this keyword works inside arrow functions and how it
differs from regular functions.
142
In JavaScript, the this keyword inside a function refers to the object that the function is a
property of or the object that the function is called on. However, the behavior of the this
keyword inside an arrow function is different from regular functions.
In an arrow function, the this keyword is lexically scoped, meaning it takes on the value
of the this keyword in the surrounding code. The this keyword in an arrow function does
not get rebound when the function is invoked, unlike regular functions. It keeps the same
value as the this keyword in the surrounding code.
For example:
const obj = {
name: 'John',
printName: () => {
console.log(this.name);
}
};
obj.printName(); //undefined
In this example, the this keyword inside the arrow function refers to the this of the global
scope, which is undefined because the name property is not defined on the global
object.
Another example:
const obj = {
name: 'John',
printName() {
console.log(this.name);
},
printNameWithArrow: () => {
console.log(this.name);
143
}
};
obj.printName(); //John
obj.printNameWithArrow(); //undefined
In this example, the printName function will output 'John' because this keyword refers to
the obj object. But printNameWithArrow function will output undefined because it has not
access to obj object this keyword.
Because of this behavior, arrow functions are not suitable for methods that need to be
bound to a specific object, and they can't be used as constructors, or with new keyword.
Conclusion :
It's important to keep in mind that arrow functions' behavior with this keyword is different
from regular functions. This means that if you want to use the this keyword inside a
function, you should use a regular function instead of an arrow function. Understanding
the this keyword in arrow functions is crucial for writing efficient and maintainable code in
JavaScript. With this knowledge, you can make better use of JavaScript's powerful
features and write more robust and readable code.
144
Code 1: Object Literal Notation
In JavaScript, the this keyword inside a function refers to the object that the function is a
property of or the object that the function is called on. However, the behavior of the this
keyword inside an arrow function is different from regular functions.
One way to create objects in JavaScript is using object literal notation. This approach
involves defining the object properties and methods within curly braces. Here's
an example:
const student = {
fullName: "Ram",
father: "Sam",
age: 12,
address: "cherry road",
city: "salem",
about: function () {
return `${this.fullName} is from ${this.city}`;
},
eligibility: function () {
return this.age>= 18;
},
};
This code creates a student object with several properties, including fullName, father,
age, address, and city. It also has two methods, about and eligibility.
Another approach to creating objects is using a factory function. This involves creating a
function that returns a new object with the desired properties and methods. Here's
an example:
const studentMethod = {
about: function () {
return `${this.fullName} is from ${this.city}`;
},
eligibility: function () {
return this.age>= 18;
145
},
};
This code creates a function addStudent that takes in several parameters for the
student's properties and then creates an empty object. The function then sets the
object's properties and methods using the studentMethod object, which contains the
shared methods.
A third approach is using prototype inheritance. This involves creating a prototype object
with shared methods and properties, and then creating new objects that inherit from the
prototype. Here's an example:
const studentMethod = {
about: function () {
return `${this.fullName} is from ${this.city}`;
},
eligibility: function () {
return this.age>= 18;
},
};
146
function addStudent(fullName, father, age, address, city) {
const user = Object.create(studentMethod);
user.fullName = fullName;
user.father = father;
user.age = age;
user.age = age;
user.address = address;
user.city = city;
return user;
}
This code is similar to Code 2, but it uses Object.create to create a new object that
inherits from studentMethod. This means that the new object has access to all the
methods and properties defined in studentMethod.
In summary, there are different ways to create objects in JavaScript, and each approach
has its own advantages and disadvantages. Table below provides a quick comparison of
the three approaches discussed in this blog post.
Object Literal Simple and easy to read Does not allow for creating
Notation multiple instances
In conclusion, choosing the right approach for creating objects in JavaScript depends on
the requirements of your project and your own coding preferences. By understanding the
different approaches and their tradeoffs, you can make informed decisions and write
more efficient and effective code.
147
Understanding Prototype and Prototypal Inheritance in
JavaScript
Prototype is an object that serves as a template for other objects. Every object in
JavaScript has a prototype, which allows the object to inherit properties and methods
from the prototype. To access an object's prototype, you can use the prototype property.
For example, to access the prototype of an object named "myObject," you can use the
code "myObject.prototype".
Prototypal Inheritance is the mechanism that allows objects to inherit properties and
methods from their prototypes. When you create a new object in JavaScript, it
automatically inherits properties and methods from its prototype. You can add new
properties and methods to an object's prototype using the prototype property. For
example, if you want to add a new method to the prototype of an object
named "myObject," you can use the code "myObject.prototype.newMethod =
function(){}".
Using Prototype and Prototypal Inheritance in JavaScript can help you create more
efficient and scalable code. By using prototypes, you can avoid duplicating code and
create objects that share common properties and methods. Prototypal Inheritance allows
you to create objects that inherit properties and methods from their prototypes, which
can reduce the amount of code you need to write and make your code easier to
148
maintain. Here are some examples that illustrate how prototype and prototypal
inheritance work in JavaScript:
In this example, we define a Person constructor function that creates a new object with a
name property. We then use the prototype property to add a new greet method to the
Person object's prototype. Finally, we create a new Person object and call the greet
method, which outputs a greeting message with the person's name.
Example 2:
let obj1 = {
name: "Joes",
city: "salem",
info: function () {
return `${this.name} is from ${this.city}`;
},
};
In the above code, we first define an object obj1 with three properties: name, city, and
info. The info property is a method that returns a string containing the name and city
149
properties. We then create a new object obj2 using the Object.create() method, with obj1
as its prototype. This means that obj2 inherits all properties and methods of obj1. In
other words, obj2 is a new object that is linked to obj1 through its prototype chain.
Finally, we modify the name property of obj2 to be "Raja". This creates a new name
property on obj2 that shadows the name property of obj1. When we access the name
property of obj2, it returns "Raja", and when we access the name property of obj1, it
returns "Joes".
Here's an example of how you can access the properties and methods of obj1 and obj2:
As you can see, obj2 inherits the info method from obj1, and when we call it on obj2, it
uses the name property of obj2 instead of obj1. This is an example of prototypal
inheritance, where objects inherit properties and methods from their prototype chain.
150
//console
obj.toString();
function myFunction() {}
/*
arr.__proto__
Array.prototype
All are object in JS
arr.__proto__.__proto__ =>Object.prototype
arr.__proto__.__proto__.__proto__ => null
obj.__proto__ =>Object.prototype
obj.__proto__.__proto__ => null
myFunction.__proto__ =>Function.prototype
myFunction.__proto__.__proto__ =>Object.prototype
myFunction.__proto__.__proto__.__proto__ => null
*/
let obj1 = {
name: "Joes",
city: "salem",
info: function () {
return `${this.name} is from ${this.city}`;
},
};
/*
let obj2 = {
name: "Raja",
};
//console
//obj2.__proto__
//obj2.__proto__ = obj1;
*/
const obj2 = Object.create(obj1);
obj2.name = "Raja";
//obj2.name;
//obj2.city;
//obj2.info();
151
obj2.city = "Chennai";
obj2.info();
Array.prototype.doubleLength = function () {
return this.length * 2;
};
//arr.__proto__
Function.prototype.mybind = function () {
console.log("This is bind function in prototype");
};
function fun() {}
function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
console.log(`Hello, my name is ${this.name}.`);
};
152
efficient way. In this blog, we will dive into the concept of class and inheritance in
JavaScript and show you how to implement them using ES5 and ES6 syntax.
A class is a blueprint for creating objects that share common properties and methods. In
JavaScript, a class is defined using the class keyword in ES6 or the function keyword in
ES5. A class can have a constructor that is called when an object is created, and it can
also have methods that define the behavior of the object.
Inheritance is a way of creating a new class from an existing class, called the parent or
base class. The new class is called the child or derived class and inherits all the
properties and methods of the parent class. In JavaScript, inheritance is achieved
through the use of the prototype chain.
ES5 Example
Let's start with an example of a class and inheritance using ES5 syntax.
153
// Add method to child class
Student.prototype.eligiblity = function () {
console.log (this.name +" age is "+this.age +" " + (this.age>= 18? "Eligibl
e”: "Not Eligable"));
};
Firstly, a parent class Person is defined with a constructor that accepts a name
parameter and assigns it to a property with the same name. A method called sayHello()
is added to the Person.prototype object, which logs a greeting with the name property of
the instance.
Next, a child class Student is defined that inherits from the Person class. It accepts two
parameters - name and age. It calls the parent constructor using Person.call(this, name)
with this referring to the Student instance and assigns the age parameter to its own age
property.
Two instances of classes are created - person using the Person constructor with the
name "Joes" and student using the Student constructor with the name "Joes" and age
35.
154
Methods are then called on the instances. person.sayHello() logs "Hello, my name is
Joes". student.sayHello() also logs "Hello, my name is Joes" because it inherits the
sayHello() method from the Person class. student.eligibility() logs "Joes age is 35
Eligible" because the age property is greater than or equal to 18.
ES6 Example
Now let's see how the same class and inheritance can be implemented using ES6
syntax.
155
let student = new Student("Joes", 35);
The code defines two classes in JavaScript, one parent class named Person and a child
class named Student that inherits from the Person class.
The Person class is defined using the class keyword with a constructor method that sets
the name property of the class. It also has a method called sayHello() which logs a
message to the console that includes the name property of the class.
The Student class is defined using the extends keyword which tells JavaScript that this
class inherits from the Person class. It has its own constructor method that takes two
arguments name and age. The super() method is called in the Student constructor to call
the constructor of the parent Person class with the name argument. The age property is
then set on the Student instance.
The Student class also has its own method called eligiblity() which logs a message to
the console. The message checks whether the age property of the Student instance is
greater than or equal to 18 and outputs either "Eligible" or "Not Eligible" accordingly.
After defining the classes, two instances of the classes are created using the new
keyword. The sayHello() and eligiblity() methods are called on these instances to log
messages to the console.
In summary, the code demonstrates how to define a parent class and a child class that
inherits from the parent class in JavaScript using the ES6 syntax. It also shows how to
define and use properties and methods on the classes and their instances.
Conclusion
In summary, class and inheritance are important concepts in JavaScript that allow you to
create reusable code and organize your program in a more efficient way. In this blog, we
have shown you how to implement class and inheritance using both ES5 and ES6
syntax. Understanding these concepts and how to use them effectively can help you
write better, more maintainable code in your JavaScript projects.
156
Understanding Getters and Setters in JavaScript
JavaScript is a versatile programming language that offers many powerful features for
creating dynamic and interactive web applications. One of these features is the ability to
define getters and setters for object properties. Getters and setters are functions that
allow you to control the way that properties are accessed and modified, and they can be
particularly useful in object-oriented programming.
getters and setters are special functions that allow you to control the way that object
properties are accessed and modified. Getters are functions that are called when you try
to access a property, and setters are functions that are called when you try to modify a
property. They are often used in object-oriented programming to encapsulate and
control the behavior of object properties.
const obj = {
get propertyName() {
// code to get the property value
},
set propertyName(value) {
// code to set the property value
}
};
The get keyword is used to define a getter, and the set keyword is used to define
a setter. The name of the property being accessed or modified is used as the function
name (in this example, propertyName). The getter function should return the value of the
property, while the setter function should update the value of the property based on the
argument passed to it.
Let's look at a couple of examples of how getters and setters work in JavaScript.
157
Example 1: Getters and Setters with Object Literals
const person = {
firstName: 'Tutor',
lastName: 'Joes',
get fullName() {
return this.firstName + ' ' + this.lastName;
},
set fullName(name) {
const parts = name.split(' ');
this.firstName = parts[0];
this.lastName = parts[1];
}
};
In this example, the get fullName() function is called when we access the fullName
property, and the set fullName() function is called when we set the fullName property.
This allows us to encapsulate the behavior of the fullName property and ensure that it is
always formatted correctly.
In this example, we use a class definition to define a Circle class that has a radius
property and two getters (diameter and area) and one setter (diameter).
class Circle {
constructor(radius) {
this.radius = radius;
158
}
get diameter() {
return this.radius * 2;
}
set diameter(diameter) {
this.radius = diameter / 2;
}
get area() {
return Math.PI * this.radius * this.radius;
}
}
myCircle.diameter = 12;
console.log(myCircle.radius); // output: 6
console.log(myCircle.diameter); // output: 12
console.log(myCircle.area); // output: 113.09733552923254
In this example, the diameter setter allows us to set the radius property based on a
given diameter value, while the diameter getter and the area getter allow us to retrieve
information about the circle. This allows us to abstract away the details of how the circle
is represented and focus on its properties and behavior.
In conclusion, getters and setters are a powerful tool in JavaScript that allow us to
encapsulate and control the behavior of object properties. By using getters and setters,
we can create more robust and maintainable code that is easier to work with and
understand.
159
Understanding Static Methods and Properties in
JavaScript
Static methods and properties are defined using the static keyword before the method or
property name. This tells JavaScript that the method or property should be associated
with the class itself, rather than with instances of the class.
160
class MyClass {
static myStaticMethod() {
console.log('Hello from a static method!');
}
}
In this example, we define a static method called myStaticMethod on the MyClass class.
We can then call this method directly on the class, without creating an instance of the
class first.
class MyClass {
static myStaticProperty = 'Hello from a static property!';
}
Static methods and properties are useful when you need to define functionality or data
that is shared among all instances of a class, or when you need to perform a task that is
not specific to any particular instance of a class.
For example, a utility class might contain a static method that performs a calculation or
converts data between formats. A configuration class might contain a static property that
stores global configuration settings.
Static methods and properties can also be used to enforce constraints or rules that apply
to all instances of a class. For example, a class that represents a set of mathematical
functions might have a static property that specifies the maximum or minimum input
value for all functions in the set.
161
Here are some more examples of static methods and properties in JavaScript:
You can use a static class to create a collection of utility functions that can be used
throughout your application. For example, let's say you have a MathUtils class that
provides various math-related functions:
class MathUtils {
static add(a, b) {
return a + b;
}
static subtract(a, b) {
return a - b;
}
static multiply(a, b) {
return a * b;
}
static divide(a, b) {
return a / b;
}
}
In this example, the MathUtils class provides four static methods for performing basic
math operations. Because they are static methods, they can be called directly on the
class without needing to create an instance of the class.
162
Example 2: Singleton Pattern
You can also use a static property to create a singleton pattern in JavaScript. The
singleton pattern ensures that only one instance of a particular class can be created.
class Database {
static instance = null;
static getInstance() {
if (!Database.instance) {
Database.instance = new Database();
}
return Database.instance;
}
query(sql) {
// code to execute SQL query
}
}
In this example, the Database class has a static property called instance that is set to
null by default. The getInstance() method checks if the instance property has been set
and creates a new instance of the Database class if it hasn't. Once an instance has
been created, the getInstance() method returns it. By doing this, we can ensure that only
one instance of the Database class is created, even if we call getInstance() multiple
times.
Example 3: Constants
Finally, you can use a static property to define a constant value that is associated with a
class. For example:
class Colors {
static RED = '#ff0000';
163
static GREEN = '#00ff00';
static BLUE = '#0000ff';
}
In this example, the Colors class defines three static properties that represent commonly
used colors. By doing this, we can easily reference these colors throughout our code
without needing to remember the hex values for each one.
Static methods and properties can be a powerful tool for creating flexible and reusable
code in JavaScript. By associating functions and variables with a class rather than with
instances of the class, you can create functionality that is more modular and easier to
maintain.
Conclusion
Sets are a data structure in JavaScript that allow you to store unique values of any type.
In this blog, we will cover everything you need to know about sets in JavaScript,
including their syntax, methods, and practical use cases.
164
Method Description
entries() Returns an iterator that contains the [value, value] pairs for each value
in the set.
forEach() Executes a provided function once for each value in the set, in
insertion order.
keys() Returns an iterator that contains the values for each value in the set.
values() Returns an iterator that contains the values for each value in the set.
Creating Sets:
You can create a set in JavaScript by using the built-in Set constructor. Here is an
example:
This creates an empty set. You can also pass an iterable object, such as an array, into
the constructor to create a set with initial values:
165
Adding and Removing Values:
mySet.add(4);
You can remove a value from a set using the delete() method:
mySet.delete(3);
You can check the size of a set using the size property:
console.log(mySet.size); // Output: 3
You can check if a value exists in a set using the has() method:
entries()
Here's an example of how to use the entries() method to iterate over the [value, value]
pairs for each value in a set:
166
console.log(iterator.next().value); // Output: ['banana', 'banana']
console.log(iterator.next().value); // Output: ['cherry', 'cherry']
In this example, we create a set set with the values 'apple', 'banana', and 'cherry'. We
then use the entries() method to create an iterator that contains the [value, value] pairs
for each value in the set.
We use the next() method on the iterator to iterate over each pair. The next() method
returns an object with a value property that contains the next [value, value] pair in the
iteration, as well as a done property that indicates whether the end of the iteration has
been reached. Note that since sets only contain unique values, the entries() method
returns pairs with the same value for both the key and the value. However, the entries()
method is still useful for iterating over the values in a set in a consistent order.
keys()
Here's an example of how to use the keys() method to iterate over the values in a set:
In this example, we create a set set with the values 'apple', 'banana', and 'cherry'. We
then use the keys() method to create an iterator that contains the keys (i.e., the values
themselves) for each value in the set.
We use the next() method on the iterator to iterate over each key. The next() method
returns an object with a value property that contains the next key in the iteration, as well
as a done property that indicates whether the end of the iteration has been
reached.Note that the keys() method is equivalent to the values() method, since sets
only contain unique values. However, the keys() method is still useful for iterating over
the values in a set in a consistent order.
In addition to these methods, there are also some static methods for sets:
167
Method Description
These inbuilt methods and static methods make working with sets in JavaScript easier
and more efficient.
from()
Here's an example of how to use the from() method to create a new set from an array:
In this example, we create an array arr with some duplicate values. We then use the
from() method to create a new set set from the array. The resulting set contains only the
unique values from the original array, since sets can only contain unique values.
We can also use the from() method to create a new set from a string:
In this example, we create a string str and use the from() method to create a new set set
from the string. The resulting set contains each character in the string as a separate
value.Note that the from() method can also be used with other iterable objects, such as
maps or arrays of arrays. This makes it a very versatile method for creating sets from
existing data structures.
168
isSet()
Here's an example of how to use the isSet() method to check if a provided value is a set
In this example, we create a set set and use the isSet() method to check if it is a set.
Since set is a set, the method returns true. We then create an array arr and use the
isSet() method to check if it is a set. Since arr is not a set, the method returns false.
The isSet() method can be useful in situations where you need to check the type of a
value before performing certain operations on it.
of()
Here's an example of how to use the of() method to create a new set with a variable
number of arguments:
In this example, we use the of() method to create a new set set with the values 1, 2, and
3. The resulting set contains these values as separate values.
We can also use the of() method to create a set with a single value:
In this example, we create a new set set with the value 1. The resulting set contains this
value as a single value. Note that the of() method is a static method, which means that it
is called on the Set constructor rather than on an instance of the Set class. This allows
us to create a new set without having to first create an empty set and then add values to
it.
Tag Widget
Here is the real time example for unique tag widget for website or blog.
169
class TagsInput {
constructor() {
this.tags = new Set();
}
addTag(newTag) {
this.tags.add(newTag);
console.log(this.tags);
}
}
Conclusion:
In this blog, we covered the basics of sets in JavaScript, including their syntax, methods,
and practical use cases. By using sets, you can easily manage collections of unique
values in your code.
170
In JavaScript, a Map is a collection of key-value pairs, where each key is unique, and it
can hold any type of values like objects, primitives, and other maps. In this code, we will
learn about various methods and properties of the Map object in JavaScript.
Method Description
Map.prototype.set(key, value) Sets the value for the specified key in the map.
To create a new Map object, we use the Map() constructor function. The code initializes
an empty Map object and assigns it to the variable userMap:
171
const userMap = new Map();
To add a new key-value pair to the Map, we use the set() method. The following code
adds four key-value pairs to the userMap:
userMap.set("name", "Joes");
userMap.set("age", 30);
userMap.set("city", "Salem");
userMap.set("contact", "9043017689");
To print a Map object, we can simply log it to the console. The following code logs the
userMap to the console:
console.log(userMap);
To update the value of an existing key in the Map, we can simply use the set() method
again with the same key. The following code updates the age of the user in the
userMap:
userMap.set("age", 31);
console.log(userMap);
Map Size:To get the size of a Map object, we can use the size property. The following
code logs the size of the userMap:
To remove a key-value pair from the Map, we can use the delete() method. The
following code removes the city from the userMap:
172
Retrieving a Value from a Map:
To retrieve the value of a key from the Map, we can use the get() method. The following
code retrieves the value of the name key from the userMap:
console.log(userMap.get("name"));
To check if a key exists in the Map, we can use the has() method. The following code
checks if the name and city keys exist in the userMap:
console.log(userMap.has("name"));
console.log(userMap.has("city"));
We can iterate over the keys and values of a Map using a for...of loop with destructuring.
The following code logs each key-value pair of the userMap to the console:
We can retrieve all the keys of a Map using the keys() method. The following code logs
each key of the userMap to the console:
We can retrieve all the values of a Map using thevalues() method. The following code
logs each value of the userMap to the console:
173
}
We can retrieve all the entries of a Map using theentries() method. The following code
logs each entry of the userMap to the console:
This code snippet uses the entries() method of a Map object to iterate over its key-value
pairs and log them to the console. Here's how it works:
• The entries() method returns an iterator object which iterates over the Map's key-
value pairs. Each iteration returns an array with two elements: the key and the
• The for...of loop is used to iterate over the iterator and execute a block of code for
each iteration. Inside the loop, we use array destructuring to assign the key and
value of the current pair to the variables key and value, respectively.
Finally, we log the key-value pair to the console using string interpolation with a template
literal.
We can retrieve all the key-value of a Map using theforEach() method. The following
code logs each key-value of the userMap to the console:
This code snippet uses the forEach() method of a Map object to iterate over its key-
value pairs and log them to the console. Here's how it works:
174
• The forEach() method takes a callback function as its argument, which is
executed for each key-value pair in the Map. The callback function receives two
• Inside the callback function, we log the key-value pair to the console using string
Overall, this code snippet accomplishes the same thing as the previous one (iterating
over a Map's key-value pairs and logging them to the console), but uses
the forEach() method instead of a for...of loop with the entries() method. Both
approaches are valid and have their own advantages depending on the situation.
The clear() method is a built-in method of the Map object in JavaScript. It is used to
remove all key-value pairs from a Map object. Here are some examples of how the
clear() method can be used with Map:
userMap.clear();
console.log("After Clear :", userMap);
This code snippet calls the clear() method on a Map object, which removes all key-value
pairs from the Map. Here's how it works:
• The clear() method is a built-in method of a Map object that removes all key-
value pairs from the Map. After calling this method, the Map will be empty.
• After calling clear(), the code logs a message to the console with the contents of
the Map. Since the Map has been cleared, the output will show an empty Map
object.
Overall, this code snippet demonstrates how to use the clear() method to remove all key-
value pairs from a Map object. It can be useful when you want to reset the Map to an
empty state.
175
Relation with Array objects
In JavaScript, a Map object is a collection of key-value pairs that allows keys of any type,
including objects, to be used as keys. A Map object can be created from an array of
arrays, where each sub-array contains two elements, the key and the value. Here's an
example:
const arr = [
["key1", "value1"],
["key2", "value2"],
];
const myMap = new Map(arr);
console.log(myMap);
console.log(myMap.get("key1"));
In the above code, an array of arrays arr is created, where each sub-array contains a
key-value pair. A Map object myMap is created from the array arr. The console.log
statements print the Map object and the value associated with the key "key1". To convert
a Map object to an array, we can use the Array.from() method. Here's an example:
console.log(Array.from(myMap));
The Array.from() method creates a new array from an array-like object, which in this
case is the Map object myMap. The resulting array will contain arrays with two elements,
the key and the value.In summary, the above code shows how to create a Map object
from an array of arrays and how to convert a Map object to an array using the
Array.from() method. This can be useful when working with collections of key-value pairs
in JavaScript.
The spread operator (...) can be used to spread the elements of an iterable object, such
as an array or a Map object, into a new array or object. When used with a Map object,
the spread operator creates an array of arrays containing the key-value pairs of the Map
object.
Here's an example:
console.log([...myMap]);
176
In the above code, the spread operator is used to create a new array containing the key-
value pairs of the Map object myMap.
To create an array of the keys or values of a Map object, we can use the
Map.prototype.keys() or Map.prototype.values() methods, respectively. These methods
return an iterable object that can be converted to an array using the Array.from()
method.
Here are examples of how to create arrays of the keys and values of a Map object:
console.log(Array.from(myMap.keys()));
console.log(Array.from(myMap.values()));
In the above code, the Array.from() method is used to convert the iterable objects
returned by myMap.keys() and myMap.values() to arrays.In summary, the spread
operator can be used to create an array of arrays containing the key-value pairs of a
Map object, while the Map.prototype.keys() and Map.prototype.values() methods can be
used to create arrays of the keys or values of a Map object.
Maps are a useful data structure in JavaScript that allow you to store key-value pairs.
They are similar to objects, but offer more flexibility and functionality. However, when
working with Maps, it's important to be aware of some common mistakes that developers
can make. In this blog post, we will discuss these mistakes and show you how to avoid
them.
One common mistake is to use the wrong syntax to set values in a Map. This can
happen when developers try to set values using the same syntax as they would use for
an object. For example:
This is incorrect because Maps are not meant to be accessed like objects. Instead, you
should use the set() method to add key-value pairs to a Map:
177
const correctMap = new Map();
correctMap.set("key1", "Data1");
correctMap.set("key2", "Data2");
Another mistake that developers make is to assume that a key exists in a Map without
checking for it first. This can result in errors or unexpected behavior. To avoid this, you
should always use the has() method to check if a key exists before trying to access its
value:
if (myMap.has("key1")) {
console.log(myMap.get("key1"));
}
Maps can use any type of value as a key, not just strings. However, if you try to use a
non-string value as a key, it will be converted to a string. This can lead to unexpected
results if you are not aware of it. To avoid this, you should always use the same type of
value for a key that you intend to use when you retrieve it later:
myMap.set(objKey, "value1");
myMap.set(arrKey, "value2");
console.log(myMap.get(objKey)); // "value1"
console.log(myMap.get({})); // undefined
console.log(myMap.get(arrKey)); // "value2"
console.log(myMap.get([])); // undefined
178
In this example, we use an object and an array as keys. If we try to retrieve the values
using a different object or array, we will get undefined. This is because the keys are not
the same object or array, even though they may have the same content.
Best Practices
• Use the has() method to check if a key exists before trying to access its value.
• Use the same type of value for a key that you intend to use when you retrieve it
later.
By following these best practices, you can avoid common mistakes and use Maps
effectively in your code.
In JavaScript, NaN stands for "Not a Number" and is a special value that represents an
unrepresentable or undefined value in a numeric context. One interesting feature of NaN
is that it is not equal to any other value, including itself. This can make it a useful value
to use as a key in Maps, but it also presents some challenges. In this blog post, we will
explore how to use NaN as a key in Maps and some of the issues to be aware of.
Code Explanation
console.log(Number("Ram"));
const myMaps = new Map();
myMaps.set(NaN, "Not a Number");
console.log(myMaps.get(NaN));
The first line attempts to convert the string "Ram" into a number using the Number()
function. Since "Ram" cannot be converted into a number, the result will be NaN.
Next, we create a new Map called myMaps and use the set() method to add a key-value
pair to it. The key is NaN and the value is the string "Not a Number".
Finally, we use the get() method to retrieve the value associated with the key NaN from
the map and log it to the console. The result will be "Not a Number".
179
Challenges of Using NaN as a Key
One of the main challenges of using NaN as a key in a Map is that NaN is not equal to
any other value, including itself. This means that you cannot use the has() method to
check if a key exists in a Map that is equal to NaN. Instead, you must use the isNaN()
function to check for NaN explicitly:
console.log(myMap.has(NaN)); // false
console.log(isNaN([...myMap.keys()][0])); // true
In this example, we use the spread operator ... to convert the Map's keys into an array
and then access the first key in the array. We then use the isNaN() function to check if
this key is equal to NaN. The result will be true.
Another challenge of using NaN as a key is that it can cause unexpected behavior
when used with certain operations, such as sorting:
In this example, we create a Map with three key-value pairs. When we use the spread
operator and the sort() method to sort the entries, the NaN value will always be sorted to
the end of the list. This is because NaN is not equal to any other value and cannot be
compared using normal comparison operators.
Best Practices
To use NaN effectively as a key in your Map, follow these best practices:
180
• Be aware of the potential for unexpected behavior when using NaN with certain
By following these best practices, you can use NaN effectively as a key in your Maps
without running into unexpected issues.
In JavaScript, maps can be merged using the spread operator and an array. This allows
you to combine the key-value pairs from multiple maps into a new map.
Here's an example of how to merge two maps using the spread operator:
This code demonstrates how two maps can be merged into a new map using the spread
operator and an array.
In this example, we have two maps: first and second. first contains three key-value pairs,
while second contains only two. We want to merge these maps into a new map called
merged.
To do this, we create a new Map object and use the spread operator (...) to add the
contents of both first and second maps to the new map. We also include an additional
181
key-value pair [1, "Ist"] to overwrite the existing value for key 1 from first with the value
"Ist". This means that the final value for key 1 in merged will be "Ist".
We then use the get() method to retrieve the values for each key in merged and log
them to the console. The output will be:
we will explore how to count the frequency of words in a sentence using JavaScript.
We can start by splitting the sentence into an array of words using the split() method. We
pass a space " " as an argument to split the sentence into individual words:
const sentence = "Fear leads to anger anger leads to hatred hatred leads to
conflict";
const words = sentence.split(" ");
console.log(words);
Next, we create a Map() object to store the frequency of each word. We loop through
each word in the words array and check if it already exists in the wordFrequency map
using the has() method. If it exists, we increment the value of the corresponding key in
the map using the get() and set() methods. If it does not exist, we set the value of the
corresponding key to 1
182
if (wordFrequency.has(word)) {
wordFrequency.set(word, wordFrequency.get(word) + 1);
} else {
wordFrequency.set(word, 1);
}
}
console.log(wordFrequency);
Map(6) {
'Fear' => 1,
'leads' => 3,
'to' => 3,
'anger' => 2,
'hatred' => 2,
'conflict' => 1
}
As we can see, the frequency of each word has been counted correctly. This technique
can be useful for a variety of applications, such as analyzing text data or generating
word clouds.
we will explore how to group objects in an array by a specific property value using
JavaScript.
const people = [
{ name: "Raja", age: 30 },
{ name: "Sara", age: 25 },
183
Our goal is to group the objects in the array by age. In other words, we want to create a
Map() object where each key is an age and the corresponding value is an array of
objects with that age.
We can start by creating an empty Map() object to store the grouped objects:
Next, we loop through each object in the people array and extract the age property. We
check if the peopleByAge map already has a key with the same age using the has()
method. If it exists, we get the value of the corresponding key using the get() method
and push the current object into the array. If it does not exist, we create a new key-value
pair where the key is the age and the value is an array containing the current object.
peopleByAge.get(age).push(person);
} else {
peopleByAge.set(age, [person]);
}
}
console.log(peopleByAge);
Map(2) {
30 => [ { name: 'Raja', age: 30 }, { name: 'Suresh', age: 30 } ],
25 => [ { name: 'Sara', age: 25 }, { name: 'Sundar', age: 25 } ]
}
184
As we can see, the objects in the array have been grouped by age using the Map()
object. This technique can be useful for a variety of applications, such as filtering or
sorting data based on specific properties.
In JavaScript, it is often useful to count the frequency of elements in an array. This can
be achieved using a Map, which allows for efficient key-value pair storage and retrieval.
Here is an example function that counts the frequency of each element in an array:
function frequencyCounter(arr) {
const map = new Map();
for (let i = 0; i<arr.length; i++) {
const element = arr[i];
map.set(element, (map.get(element) || 0) + 1);
}
return map;
}
The frequencyCounter function takes an array as input and returns a Map object with the
frequency of each element. The function first initializes an empty Map object. It then
iterates over the input array and sets each element as a key in the Map object. If the key
already exists, the function increments the value of the key by 1. Otherwise, it sets the
value of the key to 1.
In the first example, the frequencyCounter function takes an array with 7 elements, and
returns a Map object with 4 keys, each representing a unique element in the input array,
185
and their corresponding values indicating the number of times the element appears in
the input array.
In the second example, the frequencyCounter function takes an array with 4 elements,
and returns a Map object with 3 keys, each representing a unique element in the input
array, and their corresponding values indicating the number of times the element
appears in the input array.
In summary, the frequencyCounter function is a useful utility function for counting the
frequency of elements in an array using a Map object in JavaScript.
Array Destructuring:
To destructure an array, you use square brackets [] on the left-hand side of the
assignment operator =. Inside the square brackets, you define the variable names that
correspond to the array elements you want to extract. You can also use the rest operator
... to capture the remaining elements of the array into a new array.
Here's an example:
Before ES6
const numbers = [1, 2, 3, 4, 5];
186
const first = numbers[0];
const second = numbers[1];
const rest = numbers.slice(2);
console.log(first); // Output: 1
console.log(second); // Output: 2
console.log(rest); // Output: [3, 4, 5]
After ES6
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;
console.log(first); // Output: 1
console.log(second); // Output: 2
console.log(rest); // Output: [3, 4, 5]
Object Destructuring:
To destructure an object, you use curly braces {} on the left-hand side of the assignment
operator =. Inside the curly braces, you define the variable names that correspond to the
object properties you want to extract.
Here's an example:
Before ES6
const person = { name: 'Joes', age: 30, gender: 'male' };
const name = person.name;
const age = person.age;
const gender = person.gender;
console.log(name); // Output: 'Joes'
console.log(age); // Output: 30
console.log(gender); // Output: 'male'
After ES6
const person = { name: 'Joes', age: 30, gender: 'male' };
const { name, age, gender } = person;
console.log(name); // Output: 'Joes'
console.log(age); // Output: 30
187
console.log(gender); // Output: 'male'
You can also use destructuring with nested objects and arrays, and you can combine
array and object destructuring in the same statement.
Destructuring can make your code more concise and readable, especially when you're
working with complex data structures. It's a powerful feature of ES6 that's widely used in
modern JavaScript code.
You can also assign default values while using destructuring in JavaScript. To assign a
default value, you can use the = operator in the destructuring syntax.
console.log(x); // Output: 1
console.log(y); // Output: 2
console.log(z); // Output: 3 (default value)
In this example, we define an array numbers with two elements (1 and 2). We then use
array destructuring to assign the first element of the array to the variable x, the second
element to the variable y, and a default value of 3 to the variable z.Since the numbers
array has only two elements, the variable z is assigned its default value of 3.
188
In this example, we define an object person with two properties (name and age). We
then use object destructuring to assign the value of the name property to the variable
name, the value of the age property to the variable age, and a default value of 'male' to
the variable gender.
Since the person object does not have a gender property, the variable gender is
assigned its default value of 'male'.Default values in destructuring allow you to handle
cases where a property or element may be undefined or null. They provide a convenient
way to assign fallback values that ensure your code runs correctly and reliably.
For example, if you have two variables a and b and you want to swap their values, you
can use destructuring assignment like this:
let a = 1;
let b = 2;
console.log(a); // Output: 2
console.log(b); // Output: 1
Swapping using destructuring assignment is a concise and elegant way to exchange the
values of two variables and is widely used in modern JavaScript development.
189
Efficient Array Manipulation in JavaScript: Skipping Unwanted Items with
Destructuring Assignment
In JavaScript, you can skip unwanted items in an array without assigning them to local
variables by using commas to indicate the position of the items you want to skip.
For example, if you have an array myArray with five elements and you only want to
extract the first and fourth elements into local variables, you can use commas to indicate
the positions of the second, third, and fifth elements that you want to skip:
In this example, we use destructuring assignment to extract the first and fourth elements
of myArray into local variables first and fourth, respectively. We use commas to indicate
the positions of the second, third, and fifth elements that we want to skip. Note that the
commas must be included in the destructuring pattern to indicate the positions of the
items you want to skip. This allows you to extract only the values you need from an array
without having to assign all the elements to local variables.
In JavaScript, you can use destructuring and rest syntax to efficiently manipulate data in
arrays and objects. The rest syntax allows you to extract the remaining elements or
properties of an array or object into a new array or object, which you can then assign to
a single variable. This makes it easier to work with arrays and objects of varying length
and structure in JavaScript.
190
let myArray = [1, 2, 3, 4, 5, 6, 7];
console.log(first); // Output: 1
console.log(second); // Output: 2
console.log(rest); // Output: [3, 4, 5, 6, 7]
In this example, we use destructuring assignment to extract the first two elements of
myArray into local variables first and second, respectively, and the rest of the elements
into a new array rest.
And here's an example of how to use destructuring and rest syntax with objects:
console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(rest); // Output: {c: 3, d: 4, e: 5, f: 6, g: 7}
In this example, we use destructuring assignment to extract the first two elements of
myObj into local variables a and b, respectively, and the rest of the elements into a new
object rest.
Let's take a look at some examples to understand how nested destructuring assignment
works:
191
Destructuring an object with nested objects:
const user = {
name: 'Tutor Joes',
address: {
city: 'Salem',
state: 'Tamil Nadu',
country: 'India'
}
};
In this example, we have an object user with a nested object address. We use
destructuring assignment to extract the values of name, city, and state from the user
object. Note that we use the syntax address: { city, state } to destructure the nested
object.
In this example, we have an array numbers with nested arrays. We use destructuring
assignment to extract the values of a, b, c, d, e, and f from the numbers array. Note that
we use the syntax [c, d, [e, f]] to destructure the nested array.
192
const users = [
{
name: 'Tutor Joes',
address: {
city: 'Salem',
state: 'Tamil Nadu',
country: 'India'
}
},
{
name: 'Sara',
address: {
city: 'Chennai',
state: 'Tamil Nadu',
country: 'India'
}
}
];
const [{ name: name1, address: { city: city1 } }, { name: name2, address: {
city: city2 } }] = users;
console.log(name1); // 'Tutor Joes'
console.log(city1); // 'Salem'
console.log(name2); // 'Sara'
console.log(city2); // 'Chennai'
In this example, we have an array user of objects with nested objects. We use
destructuring assignment to extract the values of name1, city1, name2, and city2 from
the users array. Note that we use the syntax { name: name1, address: { city: city1 } } to
destructure the nested objects. Overall, nested destructuring assignment is a powerful
feature that can make your code more concise and readable when working with nested
data structures in JavaScript.
193
The Document Object Model (DOM) in JavaScript: An
Introduction
The Document Object Model (DOM) is a programming interface for web documents. It
represents the structure of an HTML or XML document as a tree-like structure called the
DOM tree. Each node in the tree represents an element, attribute, or piece of text in the
document.
In JavaScript, the DOM can be accessed and manipulated using the DOM API, which
allows developers to dynamically update and modify the content and style of web pages.
Using JavaScript, you can manipulate DOM elements by changing their properties,
adding or removing classes, and updating their content.
194
DOM manipulation is a core aspect of client-side web development, allowing developers
to create dynamic and interactive web pages that respond to user actions. With the
DOM, you can add event listeners to elements and respond to user events such as
clicks, hovers, and key presses.
To manipulate the DOM in JavaScript, you first need to select the elements you want to
work with using methods such as document.getElementById,
document.getElementsByClassName, and document.querySelector. Once you have a
reference to an element, you can manipulate its properties and attributes using standard
JavaScript syntax.
What is DOM ?
• The DOM is not part of the JavaScript language but is instead a Web API used to
build websites
language.
language.
and these functions are not from JavaScript but these all are provided by DOM
API
• In order to speak with DOM the browser gives us access by DOM API Application
Programming Interface.
195
1. DOM
• DOM API is the bridge between the DOM and JavaScript Engine
• We can add Event Listeners to HTML elements like (click, keyup, etc..)
Environments
• Browser environment
• Node.js environment
• Mobile environment.
196
Browser environment
The browser environment is the most commonly used JavaScript environment, which
runs JavaScript code directly in the browser. The browser provides a JavaScript engine
(such as V8 for Chrome), the DOM API for manipulating the HTML and CSS of a web
page, and other APIs for interacting with the browser, such as
the window and document objects.
Node.js environment
Mobile environment
The mobile environment includes mobile web browsers and hybrid mobile apps, which
run JavaScript code in a native environment. It provides a set of APIs for accessing
device features, such as the camera, accelerometer, and GPS.
Overall, the JavaScript environment is essential for developers to create web and mobile
applications using JavaScript. Understanding the different environments and their APIs
is crucial for developing efficient and reliable JavaScript applications.
Source Code
<html lang="en">
<head>
<title>Tutor Joes</title>
</head>
<body>
197
<h3 id="brand">Tutor Joe's</h3>
<h1>ACCESSING THE DOM</h1>
<h3 class="sub-title">JavaScript Tutorial</h3>
<p>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Necessitati
bus accusantium ab quam? Perferendis similique velit inventore, quibusdam o
mnis ad earum. Illum repellat eum saepe laboriosam
ea, a non soluta quo.
</p>
<h3 class="sub-title">DOM Tutorial</h3>
<p>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Necessitati
bus accusantium ab quam? Perferendis similique velit inventore, quibusdam o
mnis ad earum. Illum repellat eum saepe laboriosam
ea, a non soluta quo.
</p>
<script src="106_dom.js"></script>
</body>
</html>
JavaScript File
let brand = document.getElementById("brand");
console.log(brand);
console.log(brand.nodeType);
console.log(brand.nodeName);
brand.style.backgroundColor = "purple";
brand.style.color = "white";
console.log(stitle);
stitle[0].style.color = "Red";
stitle[1].style.color = "Red";
/*
stitle.forEach((element) => {
element.style.color = "Red";
});
198
*/
for (let i = 0; i < stitle.length; i++) {
stitle[i].style.color = "blue";
}
console.log(para);
This code is an example of using the Document Object Model (DOM) API in JavaScript
to manipulate the style of HTML elements on a web page.
The first line selects an HTML element with the ID "brand" using
the getElementById method and assigns it to a variable called brand. The code then
logs the brand variable to the console and retrieves information about the node type and
name of the element using the nodeType and nodeName properties.
The next few lines change the background color and text color of the brand element
using the style property.
The code then selects all elements with the class "sub-title" using
the getElementsByClassName method and assigns them to a variable called stitle. The
stitle variable is logged to the console, and the text color of each element is changed to
either red or blue using a for loop.
199
The code then selects all p elements using the getElementsByTagName method and
assigns them to a variable called para. The para variable is logged to the console, and
the text color of each element is changed to purple using a for loop.
The code then selects the first h1 element using the querySelector method and assigns
it to a variable called heading. The heading variable is logged to the console, and the
text color of the element is changed to orange using the style property.
Finally, the code selects all p elements using the querySelectorAll method and assigns
them to a variable called qpara. The qpara variable is logged to the console, and the text
color of each element is changed to blue using a forEach loop.
Overall, this code demonstrates how to select and manipulate HTML elements using the
DOM API in JavaScript.
In the Document Object Model (DOM) in JavaScript, family structure refers to the
hierarchical relationship between HTML elements on a web page. The DOM tree
represents the structure of an HTML document as a tree-like structure, where each node
in the tree represents an element, attribute, or piece of text in the document. The family
structure of DOM is also known as the parent-child relationship.
Every element in the DOM tree has a parent element, except for the root element which
is the topmost element in the tree. The parent element is the element that contains other
child elements within it. The child elements, on the other hand, are the elements that are
contained within a parent element.
The family structure of DOM allows developers to traverse and manipulate the structure
of HTML elements on a web page. Developers can access and manipulate elements by
selecting them based on their position in the DOM tree using methods such
as getElementById, getElementsByClassName, and querySelector.
200
Furthermore, developers can also manipulate the family structure of DOM by adding,
removing, or moving elements within the tree using methods such
as appendChild, insertBefore, and removeChild.
Overall, the family structure of DOM is an essential concept for web development and
provides a powerful tool for developers to create dynamic and interactive web pages.
Understanding the parent-child relationship between HTML elements is crucial for
manipulating the structure of a web page using the DOM API in JavaScript.
Example
Source Code
<html lang="en">
<head>
<title>Tutor Joes</title>
</head>
<body>
<ul>
<li>C</li>
201
<li>C++</li>
<li>Java</li>
</ul>
<script src="107_H_node.js"></script>
</body>
</html>
JavaScript File
//HTMLCollection
/*
let li = document.getElementsByTagName("li");
console.log(li);
console.log(li.length);
let element = document.createElement("li");
element.innerHTML = "JavaScript";
li[0].parentNode.appendChild(element);
console.log(li);
console.log(li.length);
for (let i = 0; i < li.length; i++) {
li[i].style.color = "orange";
}
*/
let li = document.querySelectorAll("li");
console.log(li);
console.log(li.length);
let element = document.createElement("li");
element.innerHTML = "JavaScript";
li[0].parentNode.appendChild(element);
console.log(li);
console.log(li.length);
li.forEach((element) => {
element.style.color = "orange";
});
202
li = document.querySelectorAll("li");
console.log(li);
console.log(li.length);
Creating a family tree using the DOM requires creating a hierarchical structure using
HTML elements such as <ul> and <li>. JavaScript is then used to add and remove
nodes, and manipulate the DOM to update the tree structure. CSS is used to style the
tree, such as adding colors and borders to nodes and edges.
One way to build a family tree is to start with the root node, which represents the first
family member, and then add child nodes to represent each of their children. Each child
203
node can then have child nodes of their own to represent their children, and so on. This
creates a hierarchical structure where each node has one parent and zero or more
children.
Overall, a DOM family tree can be a useful tool for visualizing family relationships and
genealogy, and JavaScript DOM manipulation provides a powerful and flexible way to
create and manipulate these structures.
For Example
<html>
<body>
<section>
<h1>This is Heading</h1>
<div>
<h2>Sample Title</h2>
<p>This is para1</p>
<p>This is para2</p>
</div>
<div>
<h2>Sample Title</h2>
<p>This is para3</p>
</div>
</section>
</body>
</html>
204
The given code is an HTML document that contains a DOM tree consisting of several
nested elements. The tree starts with the html element, which contains a body element.
Inside the body element, there is a section element that contains two div elements.
The first div element contains an h2 element, and two p elements. The
second div element contains an h2 element and a p element. The h2 and p elements are
child elements of their respective div elements.
The h1 element is a child of the section element, which makes it a sibling of the two div
elements. Similarly, the section element is a child of the body element, which makes it a
sibling of any other elements in the body.
Overall, the structure of the DOM tree can be represented as follows the image.
DOM traversing in JavaScript refers to the process of navigating the Document Object
Model (DOM) to access and manipulate elements and their properties within an HTML
document. The DOM is a tree-like structure that represents the structure of an HTML
document, where each element is represented by a node in the tree.
There are several methods in JavaScript that allow for DOM traversing, including:
205
1. parentNode and childNodes: These properties allow you to access the parent
2. nextSibling and previousSibling: These properties allow you to access the next
3. firstChild and lastChild: These properties allow you to access the first and last
These methods allow you to access elements in the DOM based on their ID,
Using these methods and properties, you can traverse the DOM to locate specific
elements and manipulate their properties, such as changing their text content or
modifying their style. DOM traversing is a powerful tool for creating dynamic and
interactive web pages in JavaScript.
parentNode
In JavaScript, a parent node refers to the node that is immediately higher in the DOM
(Document Object Model) hierarchy relative to another node.
In other words, if a particular node has child nodes, then its parent node is the
immediate node that contains it. For example, consider the following HTML code:
<div>
<h2>Sample Title</h2>
<p>This is Paragraph</p>
</div>
In this code, the parent node is the div element, which contains two child nodes, both of
which are h2 and p elements.
206
In JavaScript, you can access the parent node of an element using the parentNode
property. For example, to access the parent node of the second child p element in the
example above, you could use the following code:
const h1 = document.getElementsByTagName("h1");
console.log(h1);
const parent_h1 = h1[0].parentNode;
parent_h1.style.backgroundColor = "palevioletred";
parent_h1.style.padding = "10px";
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /
>
<title>Document</title>
</head>
<body>
<section>
<h1>This is Heading</h1>
<div>
<h2>Sample Title</h2>
<p>This is Paragraph</p>
</div>
</section>
</body>
207
</html>
In JavaScript, the terms "first child" and "last child" typically refer to the first and last
elements of a parent element's child node list.
To understand this concept, it's helpful to first understand the Document Object Model
(DOM), which is a programming interface for web documents. The DOM represents the
page as a tree-like structure, where each element is a node in the tree.
In the context of the DOM, a "parent element" is an element that contains one or more
child elements. For example, if you have an HTML document with a <div> element
208
containing several other elements, the <div> element would be the parent element, and
the other elements would be its child elements.
Using JavaScript, you can access the child nodes of a parent element using the
childNodes property. This property returns an array-like object called a NodeList, which
contains all of the child nodes of the parent element, including any text nodes or
comments.
To get the first child element of a parent element, you can use the firstElementChild
property. This property returns the first child element of the parent element, or null if the
parent element has no child elements.
Similarly, to get the last child element of a parent element, you can use the
lastElementChild property. This property returns the last child element of the parent
element, or null if the parent element has no child elements.
Here's an example that demonstrates how to get the first and last child elements of a
parent element:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /
>
<title>Document</title>
</head>
<body>
<section>
<h1>This is Heading</h1>
<div>
<h2>Sample Title</h2>
<p>This is Paragraph</p>
</div>
</section>
<script src="script.js"></script>
209
</body>
</html>
script.js
//firstChild
const firstChild = parent.firstChild;
console.log(firstChild);
//lastChild
const lastChild = parent.lastChild;
console.log(lastChild);
//firstElementChild
const firstElementChild = parent.firstElementChild;
console.log(firstElementChild);
firstElementChild.style.color = "blue";
//lastElementChild
const lastElementChild = parent.lastElementChild;
console.log(lastElementChild);
lastElementChild.style.color = "red";
console.log(h1[0].firstChild);
console.log(h1[0].firstElementChild);
console.log(h1[0].lastChild);
console.log(h1[0].lastElementChild);
//children
const div = document.getElementsByTagName("div")[0];
console.log(div);
console.log(div.children[0]);
console.log(div.children[1]);
console.log(div.childElementCount);
console.log(div.childNodes);
210
Siblings
In JavaScript, the DOM (Document Object Model) represents the HTML elements of a
web page as a tree-like structure. DOM siblings refer to the HTML elements that share
the same parent element in the DOM tree.
<div>
<h2>Sample Title</h2>
<p>This is Paragraph</p>
</div>
In this code, the parent node is the div element, which contains two child nodes, both of
which are h2 and p elements.In other words, they are all direct children of the div
element.
We can use JavaScript to access these sibling elements using various DOM methods.
For example, we can use the parentNode property to get the parent element of any of
the child elements:
We can also use the previousSibling and nextSibling properties to get the siblings of an
element. For example, we can use nextSibling to get the next sibling of the first element
It's important to note that the previousSibling and nextSibling properties return all types
of nodes, not just HTML elements. This means that we may need to use additional logic
to filter out non-element nodes.
In summary, DOM siblings in JavaScript refer to the HTML elements that share the
same parent element in the DOM tree. We can use various DOM methods to access and
manipulate these sibling elements.
211
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /
>
<title>Document</title>
</head>
<body>
<section>
<h1>This is Heading</h1>
<div>
<h2>Sample Title</h2>
<p>This is Paragraph</p>
</div>
</section>
<script src="script.js"></script>
</body>
</html>
script.js
//Siblings
const p = document.getElementsByTagName("p")[0];
console.log(p);
console.log(p.previousSibling);
console.log(p.previousElementSibling);
const h2 = document.getElementsByTagName("h2")[0];
console.log(h2);
console.log(h2.nextSibling);
console.log(h2.nextElementSibling);
212
console.log(section);
console.log(section.nextSibling);
console.log(section.nextElementSibling);
console.log(section.previousSibling);
console.log(section.previousElementSibling);
Closest
In JavaScript, the closest() method is a DOM method that allows you to traverse up the
DOM tree from a specific element and find the closest ancestor element that matches a
specified CSS selector. This method can be particularly useful when you need to find a
specific parent element that contains a certain child element.
element.closest(selector);
Here, element is the element you want to start the search from, and selector is a CSS
selector that specifies the type of element you are looking for. The closest() method
returns the closest ancestor element of element that matches the selector, or null if no
matching element is found.
<div>
<h2>Sample Title</h2>
<p>This is Paragraph</p>
</div>
If you want to find the closest ancestor element of the <p> element that has the class
"parent", you can use the closest() method like this:
213
section.style.color = "white";
section.style.padding = "10px";
This JavaScript code first selects the first <h1> element in the HTML document using the
querySelector() method and assigns it to the h1_tag variable.Then, it uses the closest()
method to find the closest ancestor element of the h1_tag that is a <section> element
and assigns it to the section variable.
Overall, this code demonstrates how to use the closest() method to find an ancestor
element based on its tag name and how to use the style property to modify the CSS
styles of an element in JavaScript.
In JavaScript, you can create, manipulate, and modify HTML elements on a webpage
using the Document Object Model (DOM). The DOM represents the webpage as a tree-
like structure of objects, where each node represents an element in the HTML
document.
2. createTextNode(text): This method creates a new text node with the specified
text.
parent node.
214
4. insertBefore(newNode, referenceNode) : This method inserts a new node before
5. removeChild : This method that is used to remove a child element from its parent
element.
6. remove : This is a newer method that allows you to remove an element directly,
These methods allow you to create and manipulate elements in the DOM dynamically
using JavaScript. This can be useful for creating dynamic user interfaces, animating
elements, and more.
createElement
The createElement() method is available on the document object, which represents the
current web page. To use it, you need to call the createElement() method and pass in
the name of the element you want to create as a string. For example, to create a new div
element, you would call
Once you have created the new element, you can manipulate it in various ways using
JavaScript. For example, you can set its attributes, add it to the DOM, or modify its
content. Here's an example
This code creates a new p element in the current HTML document using the
createElement method of the document object in JavaScript.
215
Next, the innerHTML property of the para element is set to the string "This is a
<i>Sample Paragraph</i>>". This will create a new paragraph with the text "This is a"
and an italicized "Sample Paragraph" within it.
Finally, the style.color property of the para element is set to "brown", which will change
the color of the text in the paragraph to brown.
appendChild
In JavaScript, appendChild() is a method that adds a new child node to the end of a
parent node.
The appendChild() method can also be used to move an existing element to a new
location within the DOM. Simply call appendChild() on the new parent element and pass
in the existing element as the parameter. This will remove the existing element from its
current location and place it at the end of the new parent element.
Here is an example:
The code const body = document.querySelector("body"); selects the element from the
HTML document using the querySelector method and assigns it to the body variable.
The code body.appendChild(para); appends the para element (which was created
earlier with document.createElement("p")) to the end of the body element. This is
achieved using the appendChild method which is used to add a child element to the end
of the parent element. In this case, the parent element is the body element and the child
element being added is the para element.
So, the overall effect of these two lines of code is to create a new paragraph element,
set its innerHTML to "This is a Sample Paragraph" (with the word "Sample" in italics), set
its color to brown, and then append it as a child element to the end of the element in the
HTML document.
insertBefore
216
The insertBefore method in JavaScript is used to insert a new HTML element before an
existing element on the webpage. It is a method of the parent node and allows you to
add an element to the existing DOM tree as a child element.
parentNode.insertBefore(newNode, referenceNode);
Here, parentNode is the node before which you want to insert the new node, newNode
is the node that you want to insert, and referenceNode is the node that you want to
insert the new node before.
Here is an example:
let h1 = document.createElement("h1");
h1.innerHTML = "This is Heading";
h1.style.color = "red";
body.insertBefore(h1, para);
This code creates a new h1 element using the createElement method and sets its
innerHTML to "This is Heading". The color of the text in the h1 element is set to red
using the style.color property.
Then, it uses the insertBefore method to insert the h1 element before the para element
in the body. This means that the h1 element will be placed just before the para element
in the HTML structure of the body.
removeChild
In JavaScript, the removeChild() method is used to remove a specified child node from
its parent node. It is used to manipulate the Document Object Model (DOM) of an HTML
page.
parent.parent(child);
217
where parent is the node from which we want to remove the child node and child is the
node to be removed.
Here is an example:
This JavaScript code selects all elements with a class of "btnRemove" using
the querySelectorAll() method and stores them in the removeBtns variable as a
NodeList. It then iterates through each button using the forEach() method and adds a
click event listener to each button.
When the button is clicked, the function defined in the event listener is executed. It
selects the parent node of the button twice to get the tr element that contains the button.
It then selects the sixth child node of the tr element (which is the sixth td element), and
removes it from the tr element using the removeChild() method.
Essentially, this code removes the sixth column of a table row when the corresponding
"Remove" button is clicked.
remove
In JavaScript, the remove() method is used to remove an element from the DOM. This
method is available on any DOM element and can be called directly on the element
itself.
The remove() method does not take any arguments, and simply removes the element
from the DOM, along with all its child nodes and event listeners. Once an element is
removed from the DOM, it is no longer visible on the web page.
Here is an example:
218
const removeBtns = document.querySelectorAll(".btnRemove");
removeBtns.forEach((btn) => {
btn.addEventListener("click", function () {
const tr = this.parentNode.parentNode;
//tr.remove();
});
});
This code defines a click event listener on all the elements with class
name "btnRemove" using the querySelectorAll() method. It then iterates over each
element using the forEach() method and adds a click event listener to each of them.
When a user clicks on a button with class "btnRemove", it triggers the event listener
function, which selects the parent node of the button twice to get to the table
row (tr) containing the button using parentNode property.
The code is currently commented out, but if the tr.remove() line was not commented out,
it would remove the entire table row from the HTML document using
the remove() method.
This code is useful for creating a delete function for a table row in an HTML document.
In JavaScript, the DOM (Document Object Model) provides a way to interact with the
HTML and XML documents on a web page. The output possibilities for DOM
manipulation in JavaScript are many and varied, but some common examples include:
1. Changing HTML content: You can use JavaScript to change the HTML content of
an element on a web page. For example, you can change the text of a
219
2. Modifying CSS styles: You can also use JavaScript to modify the CSS styles of
elements on a web page. For example, you can change the background color,
3. Manipulating the DOM structure: JavaScript can also be used to add, remove, or
modify elements in the DOM tree. For example, you can create new elements,
4. Responding to user input: JavaScript can be used to respond to user input, such
as mouse clicks or keyboard events. For example, you can create a button that
triggers an event when clicked, or you can listen for keyboard events to respond
to user input.
screen.
style
In JavaScript, "style" typically refers to the CSS styling of HTML elements that are
manipulated using JavaScript.
JavaScript allows you to modify the style of HTML elements by accessing their style
properties. These properties include various CSS styles such as background color, font
size, margin, padding, border, and many others. You can use the style property of an
element to change its appearance.
<h1>Tutor Joes</h1>
JavaScript code
const h1 = document.querySelector("h1");
h1.style.color = "blue";
h1.style.backgroundColor = "palegreen";
220
h1.style.padding = "20px";
This JavaScript code retrieves the first h1 element in the HTML document using
the querySelector() method and stores it in the h1 constant.The code then uses the style
property of the h1 element to modify its CSS styles dynamically.
Specifically, the first line of the code sets the color of the text inside the h1 element
to "blue" by accessing the color style property of the h1 element and setting it to
"blue".The second line sets the background color of the h1 element to "palegreen" by
accessing the backgroundColor style property of the h1 element and setting it to
"palegreen".
Finally, the third line sets the padding of the h1 element to "20px" by accessing the
padding style property of the h1 element and setting it to "20px".Overall, this code
dynamically modifies the CSS styles of the h1 element, making it have blue text on a
pale green background with a 20-pixel padding.
innerHTML
<h1>Tutor Joes</h1>
JavaScript code
const h1 = document.querySelector("h1");
h1.innerHTML = "Learn More <i>Be Smart</i>";
This JavaScript code retrieves the first h1 element in the HTML document using the
querySelector() method and stores it in the h1 constant.The code then uses the
innerHTML property of the h1 element to modify its HTML content dynamically.
Specifically, the code sets the innerHTML property of the h1 element to a new string that
contains the text "Learn More" followed by an italicized "Be Smart" text.The <i> tag in
the string is an HTML tag that stands for italic and is used to format text in italics.
221
Therefore, after executing this code, the content of the h1 element would change to
"Learn More Be Smart" with "Be Smart" displayed in italics.Overall, this code uses
the innerHTML property of the h1 element to modify its HTML content dynamically,
making it display the new text with a stylized italic format.
innerText
<h1>Tutor Joes</h1>
JavaScript code
const h1 = document.querySelector("h1");
h1.innerText = "Learn More <i>Be Smart</i>";
This JavaScript code retrieves the first h1 element in the HTML document using
the querySelector() method and stores it in the h1 constant.The code then uses the
innerText property of the h1 element to modify its text content dynamically.
Specifically, the code sets the innerText property of the h1 element to a new string that
contains the text "Learn More <i>Be Smart</i>".Note that unlike innerHTML,
using innerText would not create an italicized text for the "Be Smart" text because it
does not parse and display HTML tags. Instead, the entire string, including the <i> tag,
will be treated as plain text and displayed as such.
Therefore, after executing this code, the content of the h1 element would change to
"Learn More <i>Be Smart</i>", with the <i> tag visible as plain text instead of displaying
an italicized "Be Smart" text. Overall, this code uses the innerText property of
the h1 element to modify its text content dynamically, making it display the new string of
text with the <i> tag treated as plain text.
cloneNode()
222
In JavaScript, cloneNode() is a method that creates a copy of an HTML element and all
its child nodes. The new copy is called a "clone" and is a separate object from the
original element, with its own set of properties and attributes.
<h1>Tutor Joes</h1>
JavaScript code
const h1 = document.querySelector("h1");
const body = document.querySelector("body");
let cloneH1 = h1.cloneNode(true);
let cloneH2 = h1.cloneNode(false);
body.appendChild(cloneH1);
body.appendChild(cloneH2);
This JavaScript code selects the first h1 element and the body element from the HTML
document using the querySelector() method and stores them in the h1 and body
constants, respectively. The code then creates two new variables, cloneH1 and
cloneH2, and assigns them the result of calling cloneNode() method on the h1 element.
1. The first cloneH1 variable is created by calling cloneNode() with the argument
true. This creates a deep clone of the h1 element, which means that all of its child
argument false. This creates a shallow clone of the h1 element, which means that
only the element itself is cloned, and not its child nodes.
3. The code then appends both cloneH1 and cloneH2 to the body element using
4. In this example, after executing the code, the body element would contain two
223
5. cloneH1 would be a deep clone of the original h1 element, including all of its child
original h1 element, without any child nodes. Therefore, cloneH2 would be a new
h1 element with the same attributes and properties as the original h1 element,
7. Overall, this code demonstrates how to use cloneNode() to create deep and
shallow copies of an HTML element, which can be useful when you need to
duplicate an element and manipulate its content or style without affecting the
original source.
Using cloneNode() can be a useful way to create a copy of an HTML element and its
child nodes, which can be manipulated and modified independently of the original
element. This can be particularly useful in cases where you want to create dynamic
content or modify existing elements without affecting the original source.
setInterval()
<div class="clock"></div>
The function parameter is the name of the function to be called or a block of code to be
executed at each interval. The interval parameter is the number of milliseconds between
each call of the function.
<h1>Tutor Joes</h1>
JavaScript code
224
function clock() {
const date = new Date();
Using setInterval can be useful for creating animations, updating data on a webpage, or
performing any other task that needs to be repeated at regular intervals. However, it's
important to use it judiciously, as excessive use of setInterval can lead to performance
issues or excessive resource consumption.
2. Sets the font size of the selected element to 30 pixels using the style property
3. Defines a function named clock() that uses the Date object to get the current time
4. Updates the innerHTML property of the clockDiv element with the current time
In JavaScript, the classList and attribute methods are used for manipulating the class
and attribute values of an HTML element.
225
The classList method provides a set of built-in functions that allow developers to add,
remove, or toggle class names of an element. These functions
include add(), remove(), toggle(), and contains(). Using these functions, you can easily
change the appearance and behavior of an element based on user interaction or other
events.
On the other hand, the attribute method provides a way to get, set, or remove the
attribute value of an element. This method accepts one or two parameters: the first
parameter is the name of the attribute, and the second parameter (optional) is the new
value of the attribute.
classList
The classList property returns a DOMTokenList object, which represents the class
attribute of an element as a collection of space-separated tokens. You can use the
methods of this object to manipulate the classes of the element.Here are some common
methods of the classList object
Adding a class
The add() method belongs to the classList property, which is available on all HTML
elements. You can use the add() method to add a new class name to the list of classes
that an element already has.
Note that if the element already has a class name that you're trying to add, the add()
method will ignore that class name and not add it again. This ensures that each class
name in the list of classes is unique.
To add a new class to an element, you can use the add() method. For example:
<div class="box">Box</div>
JavaScript Code
226
1. This line of code selects the button with an id of "btnAdd" using
the addEventListener() method. The event that we're listening for is a "click"
when the event is triggered. In this case, we're passing in an anonymous function
that will add a new CSS class to a box with an unknown id.
the classList.add() method. This will apply a new style to the box, changing its
5. Note that the box variable isn't defined in this code snippet, so it's unclear what
element this code is targeting. However, assuming that there is an HTML element
with a class attribute of "box" on the page, this code would add a new CSS class
Removing a class
classList.remove() is a method in JavaScript that allows you to remove one or more CSS
classes from an HTML element.
The remove() method belongs to the classList property, which is available on all HTML
elements. You can use the remove() method to remove a class name from the list of
classes that an element already has.The remove() method belongs to the classList
property, which is available on all HTML elements. You can use the remove() method to
remove a class name from the list of classes that an element already has.
227
Note that if the element doesn't have a class name that you're trying to remove, the
remove() method will ignore that class name and not throw an error.
To remove a class from an element, you can use the remove() method. For example:
<button id="btnRemove">Remove</button>
JavaScript Code
3. This code adds an event listener to the btnRemove button using the
addEventListener() method. The event that we're listening for is a "click" event,
when the event is triggered. In this case, we're passing in an anonymous function
that will remove a CSS class from a box with an unknown id.
5. We're removing the CSS class "new-color" from the box using the
classList.remove() method. This will remove the style that was previously applied
to the box by the "new-color" CSS class, changing its background color back to
6. Note that the box variable isn't defined in this code snippet, so it's unclear what
element this code is targeting. However, assuming that there is an HTML element
228
with a class attribute of "box" on the page, this code would remove the "new-
color" CSS class from that element when the "btnRemove" button is clicked.
Toggling a class
The toggle() method belongs to the classList property, which is available on all HTML
elements. You can use the toggle() method to add a class name to an element if it
doesn't have it, or remove it if it already has it.
Note that the toggle() method returns a boolean value that indicates whether the class
was added or removed. If the class was added, the method returns true. If the class was
removed, the method returns false.
You can also use the toggle() method to conditionally add or remove a class based on a
boolean value..
To toggle a class on an element (i.e., add it if it doesn't exist, remove it if it does), you
can use the toggle() method. For example:
<button id="btnToggle">Toggle</button>
JavaScript Code
the addEventListener() method. The event that we're listening for is a "click"
when the event is triggered. In this case, we're passing in an anonymous function
that will toggle a CSS class on and off a box with an unknown id.
229
4. We're toggling the CSS class "new-color" on and off the box using
the classList.toggle() method. This method will add the "new-color" class to the
5. Assuming that there is an HTML element with a class attribute of "box" on the
page, this code would toggle the "new-color" CSS class on and off that element
Attribute
In JavaScript, the getAttribute() and setAttribute() methods are used to get and set
attributes on an HTML element, respectively.
To get the value of an attribute on an element, you can use the getAttribute()
method.The getAttribute() method takes a single argument, which is the name of the
attribute you want to get the value of. If the specified attribute doesn't exist on the
element, the getAttribute() method will return null.Note that if the attribute you want to
get is a standard HTML attribute, like href, src, or class, you can also access them
directly as properties on the HTML element
However, if you want to get the value of a custom data attribute, you must use
the getAttribute() method.
If the specified attribute doesn't already exist on the element, the setAttribute() method
will create it. If the attribute already exists, the method will replace its value with the new
value.Note that you can also set the value of standard HTML attributes, like href, class,
or id, by directly setting their corresponding properties on the HTML element.
230
However, if you want to set the value of a custom data attribute, you must use the
setAttribute() method.
For Example
JavaScript Code
btnClick.addEventListener("click", function () {
const getAtt = input.getAttribute("type");
if (getAtt == "text") {
input.setAttribute("type", "password");
} else {
input.setAttribute("type", "text");
}
});
his JavaScript code adds a click event listener to a button with the ID "btnClick". When
the button is clicked, the code retrieves the "type" attribute of an input element and
checks if it equals "text". If it does, the code sets the "type" attribute of the input element
to "password". If it doesn't, the code sets the "type" attribute to "text". This code allows a
user to toggle between hiding and showing the value of a password input field.
1. The const keyword is used to declare two variables: btnClick and input. btnClick
is assigned the value of the HTML element with the ID "btnClick", which is a
button element in this case. input is assigned the value of the first HTML input
btnClick element. The second argument of this method is a callback function that
231
3. Inside the callback function, the getAttribute() method is used to get the current
value of the type attribute of the input element, which is initially set to "text".
the setAttribute() method is used to change the value of the type attribute to
5. When the user clicks the button, the value of the type attribute of the input
element is toggled between "text" and "password", allowing the user to toggle the
Note that this method is not supported in Internet Explorer or some older browsers, so
you may want to check for its availability before using it. One way to do this is to use the
typeof operator to check if the method exists on the element
The removeAttribute() method takes a single argument, which is the name of the
attribute you want to remove.If the specified attribute doesn't exist on the element, the
removeAttribute() method will do nothing.
Note that you can also remove standard HTML attributes, like href, class, or id, by
setting their corresponding properties on the HTML element to null.
However, if you want to remove a custom data attribute, you must use
the removeAttribute() method.
To remove an attribute from an element, you can use the removeAttribute() method. For
example:
JavaScript Code
232
hasAttribute()
The hasAttribute() method takes a single argument, which is the name of the attribute
you want to check.
If the specified attribute exists on the element, the hasAttribute() method will return true.
If the attribute does not exist, the method will return false.
Note that you can also check for standard HTML attributes, like href, class, or id, by
checking their corresponding properties on the HTML element.
However, if you want to check for a custom data attribute, you must use
the hasAttribute() method.
For example:
JavaScript Code
console.log(input.hasAttribute("class"));
getAttributeNames()
Note that this method is not supported in Internet Explorer or some older browsers, so
you may want to check for its availability before using it. One way to do this is to use
the typeof operator to check if the method exists on the element:
Note that this method is not supported in Internet Explorer or some older browsers, so
you may want to check for its availability before using it. One way to do this is to use
the typeof operator to check if the method exists on the element:
For example:
JavaScript Code
233
console.log(list);
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /
>
<title>Document</title>
<style>
.box {
width: 150px;
height: 150px;
background-color: palegreen;
font-size: 20px;
text-align: center;
line-height: 150px;
margin-bottom: 20px;
}
.new-color {
color: orange;
background-color: #222;
}
</style>
</head>
<body>
<!--
<div class="box">Box</div>
<button id="btnAdd">Add</button>
<button id="btnRemove">Remove</button>
<button id="btnToggle">Toggle</button>
-->
<input type="text" id="txtName" class="apple" name="name" />
<button id="btnClick">Click</button>
<script src="script.js"></script>
234
</body>
</html>
script.js
/*
classList.add();
classList.remove();
classList.toggle();
getAttribute();
setAttribute();
hasAttribute()
getAttributeNames()
removeAttribute()
*/
/*
const btnAdd = document.querySelector("#btnAdd");
const btnRemove = document.querySelector("#btnRemove");
const btnToggle = document.querySelector("#btnToggle");
const box = document.querySelector(".box");
btnAdd.addEventListener("click", function () {
box.classList.add("new-color");
});
btnRemove.addEventListener("click", function () {
box.classList.remove("new-color");
});
btnToggle.addEventListener("click", function () {
box.classList.toggle("new-color");
});
*/
btnClick.addEventListener("click", function () {
235
const getAtt = input.getAttribute("type");
if (getAtt == "text") {
input.setAttribute("type", "password");
} else {
input.setAttribute("type", "text");
}
});
console.log(input.hasAttribute("class"));
let list = input.getAttributeNames();
console.log(list);
input.removeAttribute("name");
list = input.getAttributeNames();
console.log(list);
Mouse events in JavaScript are events that are triggered by mouse interactions on a
web page. These events allow developers to capture and respond to user actions
involving the mouse, such as clicking, moving, hovering, and dragging.
Mouse events in JavaScript are events that are triggered by mouse interactions on a
web page. These events allow developers to capture and respond to user actions
involving the mouse, such as clicking, moving, hovering, and dragging.
• "click": This event is triggered when the user clicks (presses and releases) a
• "mousemove": This event is triggered when the mouse pointer moves over an
element. It can be used to track the movement of the mouse and respond
236
• "mouseover" and "mouseout": These events are triggered when the mouse
implement hover effects or tooltips that appear when the mouse pointer is over a
certain element.
• "mousedown" and "mouseup": These events are triggered when the user
used to detect when a user starts or stops clicking on an element, which is useful
• "ondblclick": This event is triggered when the user double clicks (presses and
double clicks on a button, link, or any other clickable element on a web page.
click
In JavaScript, the "click" event is triggered when a user presses and releases a mouse
button on an element, typically the left button, within a short time frame. The "click" event
is one of the most commonly used mouse events and is often used to capture user
interactions with clickable elements on a web page, such as buttons, links, and images.
To handle the "click" event in JavaScript, an event listener can be attached to the target
element using the DOM (Document Object Model) manipulation methods. The event
listener is a function that is executed when the "click" event occurs on the specified
element.
It creates an HTML button element with an onclick attribute that specifies a JavaScript
code snippet to be executed when the button is clicked.
The onclick attribute is an example of an event handler in HTML, and it is used to define
the behavior or action to be taken when a specific event, in this case, a click event,
occurs on the HTML element to which it is attached.
237
In this case, when the button is clicked, the JavaScript code snippet alert('Welcome to
Tutor Joes')will be executed. The alert() function is a built-in JavaScript function that
displays a popup dialog box with the message "Welcome to Tutor Joes" as its content.
ondblclick
<button class="btn">Event</button>
const btn = document.querySelector(".btn");
btn.addEventListener("dblclick", function () {
alert("Your are dblclicked");
});
mousemove
The "mousemove" event is a mouse event in JavaScript that is triggered when the
mouse pointer moves over an element. It is often used to track the movement of the
mouse and respond accordingly, such as updating the position of an element or creating
interactive elements that follow the mouse cursor.
<button class="btn">Event</button>
const btn = document.querySelector(".btn");
btn.addEventListener("mousemove", function () {
this.style.backgroundColor = "purple";
});
238
mouseover
The "mouseover" event is a mouse event in JavaScript that is triggered when the mouse
pointer moves over an element or one of its child elements. It is often used to detect
when the mouse pointer enters a particular element, and is commonly used for creating
hover effects, tooltips, or other interactive elements that respond to mouse movements.
To handle the "mouseover" event in JavaScript, an event listener can be attached to the
target element using the DOM (Document Object Model) manipulation methods. The
event listener is a function that is executed when the mouse pointer moves over the
specified element or its child elements.
<button class="btn">Event</button>
const btn = document.querySelector(".btn");
btn.addEventListener("mouseover", function () {
this.style.backgroundColor = "orange";
});
mouseout
The "mouseout" event is a mouse event in JavaScript that is triggered when the mouse
pointer moves out of an element or one of its child elements. It is often used to detect
when the mouse pointer leaves a particular element, and is commonly used for creating
hover effects, tooltips, or other interactive elements that respond to mouse movements.
To handle the "mouseout" event in JavaScript, an event listener can be attached to the
target element using the DOM (Document Object Model) manipulation methods. The
event listener is a function that is executed when the mouse pointer moves out of the
specified element or its child elements.
<button class="btn">Event</button>
const btn = document.querySelector(".btn");
btn.addEventListener("mouseout", function () {
this.style.backgroundColor = "yellow";
239
});
mousedown
The "mousedown" event is a mouse event in JavaScript that is triggered when a mouse
button is pressed down on an element. It is often used to detect when a user begins to
click or interact with an element using the mouse.
<button class="btn">Event</button>
const btn = document.querySelector(".btn");
btn.addEventListener("mousedown", function () {
this.style.backgroundColor = "red";
});
mouseup
The "mouseup" event is a mouse event in JavaScript that is triggered when a mouse
button is released after being pressed down on an element. It is often used to detect
when a user finishes clicking or interacting with an element using the mouse.
To handle the "mouseup" event in JavaScript, an event listener can be attached to the
target element using the DOM (Document Object Model) manipulation methods. The
event listener is a function that is executed when a mouse button is released on the
specified element.
<button class="btn">Event</button>
const btn = document.querySelector(".btn");
btn.addEventListener("mouseup", function () {
this.style.backgroundColor = "red";
240
});
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /
>
<title>Document</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h3>JavaScri pt DOM Event Handlers</h3>
<button onclick="alert('Welcome to Tutor Joes')">Inline event</button>
script.js
/*
Event Handlers
Inline event listeners
Inline properties
Event listeners.
Event
1.Mouse
click
241
,dblclick
,mousedown
,mouseout
,mouseup
,mouseover
2.Keyboard
Keydown
keypress
keyup
keycode
code
3.Form
focus
submit
blur
change
4.Touch
touchstart
touchmove
touchend
touchcancel
5.Window
scroll
resize
load
haschange
*/
btn.addEventListener("dblclick", function () {
alert("Your are dblclicked");
242
});
btn.addEventListener("mousedown", function () {
this.style.backgroundColor = "Red";
});
btn.addEventListener("mouseout", function () {
this.style.backgroundColor = "yellow";
});
btn.addEventListener("mouseup", function () {
this.style.backgroundColor = "blue";
});
btn.addEventListener("mouseover", function () {
this.style.backgroundColor = "orange";
});
Keyboard events in JavaScript are events that are triggered when a user interacts with
the keyboard, such as pressing a key, releasing a key, or typing a key. These events
allow web developers to capture and respond to user input from the keyboard in web
applications.
• keydown event: This event is triggered when a key is initially pressed down on
the keyboard. It occurs when the physical key is first pressed down, and it may
243
• keyup event: This event is triggered when a key is released after being pressed
down on the keyboard. It occurs when the physical key is released, and it is only
• keypress event: This event is triggered when a key that represents a character
value is actually typed by the user. It occurs after the keydown event and before
the keyup event, and it is typically used to capture character input, such as in text
• key property: The key property of the event object represents the physical key
• code property: The code property of the event object represents the physical
string value that does not depend on the keyboard layout or locale.
To handle keyboard events in JavaScript, event listeners can be attached to the target
element using the DOM (Document Object Model) manipulation methods. The event
listeners are functions that are executed when a keyboard event is triggered on the
specified element.
Keydown
The keydown event is a keyboard event that is triggered when a key is initially pressed
down by the user. It is commonly used in JavaScript to capture and handle user input
from the keyboard. The keydown event is fired when the physical key is pressed down,
regardless of whether the key is subsequently held down or released.
/*document.addEventListener("keydown", handleKeyEvent);
function handleKeyEvent(event) {
const eventType = event.type;
244
console.log(`Event type: ${eventType}`);
}
*/
The code snippet provided demonstrates how to handle the keydown event in
JavaScript to validate user input in an input field with an ID of "input-num" and display an
error message in an element with an ID of "error" if the input is not a number.
1. The keydown event is attached to the document object with an event listener
2. The handleKeyEvent function logs the type of the event (keydown) to the
console.
245
4. The event listener function for the keydown event on the input element takes an
event parameter, which represents the event object that contains information
about the keydown event, such as the key that was pressed (event.key).
5. The key property of the event object is retrieved and logged to the console. This
property represents the value of the key that was pressed, such as a letter,
number, or symbol.
6. The isNaN function is used to check if the key value is not a number. If it is not a
non-numeric characters.
7. If the key value is not a number, an error message is displayed in the element
This code can be used to ensure that only numeric input is accepted in the "input-num"
field and display an error message if any non-numeric characters are entered. Note that
the keydown event is used in this example, which triggers when a key is initially pressed
down, but it may not capture certain non-character keys (such as arrow keys, function
keys, etc.). Depending on your use case, you may need to consider using other
keyboard events such as keypress or input for more robust input validation.
keypress (deprecated)
The keypress event is a keyboard event that is triggered when a key is initially pressed
down and a character is generated by the key, typically resulting in a printable character
being displayed on the screen. It is commonly used in JavaScript to capture and handle
246
user input from the keyboard when printable characters are typed, such as letters,
numbers, and symbols.
Please note that the keypress event is being deprecated in favor of the input event in
modern web standards, as it provides more consistent and reliable input handling across
different devices and input methods. However, the keypress event may still be used in
older or legacy web applications, or in specific use cases where printable character input
is required.
keyup
The keyup event in JavaScript is triggered when a key is released after being pressed
down on the keyboard. It is one of the keyboard events that can be used to detect when
a specific key is released by the user.
247
function handleKeyEvent(event) {
const eventType = event.type;
console.log(`Event type: ${eventType}`);
}
key
In JavaScript, the key property is a property of the event object that represents the value
of the key that was pressed or released during a keyboard event. It provides information
about the specific key that triggered the event, such as a letter, number, or special
character.
The key property returns a string that represents the value of the key in a human-
readable format, regardless of whether the key is uppercase or lowercase.
The key property is commonly used in keyboard event handlers to determine which key
was pressed or released, and to perform different actions based on the value of the key.
function handleKeyEvent(event) {
const keyName = event.key;
console.log(`Key name: ${keyName}`);
}
code
The "code" property may refer to a custom property that has been added to a DOM
element by a developer using their own JavaScript code. In JavaScript, it's possible to
add custom properties to DOM elements or any other JavaScript objects by simply
assigning a value to a property that doesn't already exist on the object.
248
<input type="text" id="input-num" />
document.addEventListener("keyup", handleKeyEvent);
function handleKeyEvent(event) {
const keyCode = event.code;
console.log(`Key code: ${keyCode}`);
}
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /
>
<title>Document</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Keyboard Event in JavaScript</h1>
<p>Press Any Key</p>
<hr />
<label for="input-num">Enter a Number</label>
<input type="text" id="input-num" />
<p id="error"></p>
<script src="113_event2.js"></script>
</body>
</html>
script.js
/*
2.Keyboard
Keydown
keypress (deprecated)
249
keyup
key
code
*/
document.addEventListener("keydown", handleKeyEvent);
document.addEventListener("keypress", handleKeyEvent);
document.addEventListener("keyup", handleKeyEvent);
function handleKeyEvent(event) {
const eventType = event.type;
const keyCode = event.code;
const keyName = event.key;
console.log(`Event type: ${eventType}`);
console.log(`Key code: ${keyCode}`);
console.log(`Key name: ${keyName}`);
}
//-----------------------------------------------------------
//-----------------------------------------------------------
250
Handling Form Events in JavaScript: Examples and Best
Practices
Form events in JavaScript are events that are triggered when a user interacts with a
form on a web page. These events allow you to capture and respond to user actions,
such as submitting a form, entering data into form fields, or resetting a form.
submit button or pressing the Enter key within a form field. You can use this
event to perform form validation, submit form data to a server, or handle other
form-related tasks.
2. input: This event is triggered when the value of a form field is changed by the
user. This includes events such as typing in a text input, selecting an option in a
dropdown, or changing the value of a checkbox or radio button. You can use this
3. change: This event is triggered when the value of a form field is changed and the
field loses focus. This includes events such as selecting an option in a dropdown
or changing the value of a checkbox or radio button. You can use this event to
4. reset: This event is triggered when a form is reset, either by clicking a reset
button or programmatically resetting the form using JavaScript. You can use this
251
5. focus : The focus event is triggered when an element, such as a form field,
receives focus. This typically occurs when the user clicks or tabs into an input
field.
radio button is checked or not. It is a boolean property that returns true if the
button is checked or not. It is a boolean property that returns true if the element is
To handle form events in JavaScript, you can use event listeners or event handlers.
Event listeners are functions that are registered to listen for specific events on specific
DOM elements, while event handlers are functions that are directly assigned to handle
specific events. These functions can be written in JavaScript and can manipulate the
DOM, validate form data, and perform other actions based on the user's interactions with
the form.
Form events in JavaScript are an essential part of building interactive and dynamic web
forms that provide a smooth user experience. Properly handling form events can help
you create robust and user-friendly web forms that are responsive to user input and
behavior.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /
>
<link rel="icon" type="image/ico" href="logo.png" />
<title>Document</title>
<style>
252
@import url("https://fonts.googleapis.com/css2?family=Lobster&family=
Poppins:wght@100;200;300;400;500;600;700;800&display=swap");
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
body {
width: 100vw;
height: 100vh;
background-color: palegreen;
display: flex;
justify-content: center;
align-items: center;
font-size: 12px;
}
h1 {
font-weight: 500;
text-transform: uppercase;
font-size: 14px;
}
form {
width: 300px;
background-color: #fff;
padding: 10px;
}
.form-group {
margin-bottom: 10px;
}
.form-group > label {
display: block;
padding: 3px 0;
}
input[type="text"],
input[type="email"],
select {
253
width: 100%;
outline: none;
font-size: 12px;
}
fieldset {
border: none;
}
button {
width: 100px;
border: none;
background-color: #222;
color: #fff;
padding: 2px 10px;
}
form .form-group:last-of-type {
margin-top: 10px;
}
</style>
</head>
<body>
<form action="#" autocomplete="off">
<h1>Form Events in JavaScript</h1>
<div class="form-group">
<label for="username">User Name</label>
<input type="text" id="username" />
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" />
</div>
<div class="form-group">
<label for="course">Course Name</label>
<select id="course">
<option value="">Select Course</option>
<option value="C">C</option>
<option value="C++">C++</option>
254
<option value="Java">Java</option>
</select>
</div>
<div class="form-group">
<fieldset>
<legend>Gender</legend>
<label><input type="radio" name="gender" value="male" /> Male</la
bel>
<label><input type="radio" name="gender" value="female" />Female<
/label>
</fieldset>
</div>
<input type="checkbox" id="agree" />
<label for="agree">I Agree all Condition</label>
<div class="form-group">
<button type="submit">Submit</button>
<button type="reset">Reset</button>
</div>
</form>
<script src="115_form_events.js"></script>
</body>
</html>
script.js
/*
Form Events in JavaScript
submit
reset
change
checked
blur
focus
input
*/
255
const username = document.querySelector("#username");
const email = document.querySelector("#email");
const course = document.querySelector("#course");
const checkbox = document.querySelector("#agree");
const radios = document.querySelectorAll('input[name="gender"]');
256
username.addEventListener("input", function (e) {
console.log("Username input changed:", e.target.value);
});
The provided code demonstrates the use of various form events in JavaScript, along
with some related event listeners and event handling functions. Here's a brief
explanation of the code:
• Form submit event: The submit event is triggered when the form is submitted. In
the code, an event listener is added to the form element, and when the form is
submitted, the event handling function prevents the default form submission
behavior using e.preventDefault(), and logs the form data including the values of
• Form reset event: The reset event is triggered when the form is reset. In the
code, an event listener is added to the form element, and when the form is reset,
the event handling function logs a message to the console indicating that the
• change event: The change event is triggered when the value of a form field,
the course select element, and when the selected course is changed, the event
257
added to the checkbox element, and when the checkbox is checked or
accordingly.
• input event: The input event is triggered when the value of an input field, such
the username input element, and when the username input is changed, the
• focus and blur events: The focus event is triggered when an element receives
focus, and the blur event is triggered when an element loses focus. In the code,
event listeners are added to the username input element, and when the input
element receives focus, the border color is changed to orange, and when it loses
In summary, the provided code demonstrates the use of form events in JavaScript,
including submit, reset, change, checked, input, focus, and blur events, along with
their corresponding event listeners and event handling functions. These events and
event handling functions can be used to create dynamic and interactive forms in web
applications.
Touch events are a type of event that can be triggered on touch-enabled devices, such
as smartphones and tablets, using JavaScript. They allow web developers to respond to
user interactions, such as tapping, swiping, and pinching, on touchscreens.
258
1. touchstart: This event is triggered when a finger or stylus is first placed on the
touch screen.
2. touchmove: This event is triggered when a finger or stylus is moved across the
touch screen.
3. touchend: This event is triggered when a finger or stylus is lifted off the touch
screen.
Each touch event provides information about the touch point, including the position (in
pixels) relative to the viewport, the target element being touched, and other details such
as the number of touches and their identifiers.
To handle touch events in JavaScript, you can use event listeners that are attached to
the DOM elements you want to capture touch events from. For example, you can use
the addEventListener method to listen for touch events on an element, and then use
event handlers to execute custom code when touch events occur.
Here's an example of how you can use JavaScript to handle a touch event:
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /
>
<link rel="icon" type="image/ico" href="logo.png" />
<title>Document</title>
<style>
@import url("https://fonts.googleapis.com/css2?family=Lobster&family=
Poppins:wght@100;200;300;400;500;600;700;800&display=swap");
* {
margin: 0;
padding: 0;
259
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
h3 {
font-weight: 600;
text-transform: uppercase;
}
#touchArea {
width: 400px;
height: 200px;
background-color: gray;
text-align: center;
color: white;
line-height: 200px;
font-size: 20px;
}
</style>
</head>
<body>
<h3>Touch Events in JavaScript</h3>
<div id="touchArea">Touch me!</div>
<script src="touch.js"></script>
</body>
</html>
script.js
/*
4.Touch
touchstart
touchmove
touchend
touchcancel
*/
260
touchArea.addEventListener("touchstart", function (e) {
e.preventDefault();
touchArea.style.backgroundColor = "blue";
touchArea.textContent = "Touch Started !";
});
Live Preview
The provided code sets up event listeners for touch events on an element with the id
"touchArea" using JavaScript. Let's go through each event listener and what it does:
• touchstart: This event listener is triggered when a finger or stylus is first placed
on the touch screen. It prevents the default behavior of the touchstart event
It then sets the background color of the "touchArea" element to blue and updates
261
• touchmove: This event listener is triggered when a finger or stylus is moved
across the touch screen. It also prevents the default behavior of the touchmove
element to green and updates its text content to "Touch Moved !".
• touchend: This event listener is triggered when a finger or stylus is lifted off the
• touchcancel: This event listener is triggered if the touch event is cancelled, such
sets the background color of the "touchArea" element to red and updates its text
Note that in each event listener, the e parameter represents the touch event object,
which contains information about the touch event, such as the target element, touch
coordinates, and other details. By using event listeners for touch events, you can
respond to user interactions on touch-enabled devices and customize the behavior of
your web application accordingly.
It's important to note that touch events are different from mouse events, and may require
additional considerations for handling gestures, multi-touch interactions, and
performance optimization on touch-enabled devices. Proper handling of touch events
can greatly enhance the user experience of a touch-enabled web application.
Touch events are events that are triggered when a user interacts with a touch-enabled
device, such as a smartphone or a tablet. These events allow you to capture touch
262
gestures, such as tapping, swiping, and dragging, and use them to build interactive web
applications or games.
First, you'll need to set up the HTML markup for your game. For example, you can
create a simple game container with a canvas element where you'll draw the game
graphics. You can also create any additional HTML elements, such as buttons or score
displays, that you'll need for your game.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /
>
<link rel="icon" type="image/ico" href="logo.png" />
<title>Document</title>
<style>
@import url("https://fonts.googleapis.com/css2?family=Lobster&family=
Poppins:wght@100;200;300;400;500;600;700;800&display=swap");
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
h3 {
font-weight: 600;
text-transform: uppercase;
}
#game {
width: 400px;
height: 200px;
background-color: #ddd;
position: relative;
}
263
#ball {
width: 25px;
height: 25px;
background-color: red;
border-radius: 25px;
position: absolute;
top: 75px;
left: 75px;
}
</style>
</head>
<body>
<h3>Simple Ball Game</h3>
<div id="game">
<div id="ball"></div>
</div>
<script src="touch.js"></script>
</body>
</html>
Next, you'll need to create a JavaScript file (e.g., "touch.js") that will contain the game
logic. In this file, you can define variables to store game state, such as the player's score
or the game objects' positions. You can also set up an event listener for touch events.
In the event listener functions, you can access information about the touch events, such
as the position of the touch on the screen. You can use this information to update your
game state, such as moving game objects or detecting collisions.
touch.js
const game = document.getElementById("game");
const ball = document.getElementById("ball");
let startX, startY;
264
startX = touch.clientX;
startY = touch.clientY;
});
Live Preview
This code sets up touch event listeners for a simple game where a ball can be moved
around within a container element with id "game". Let's go through it step by step:
1. The touchstart event listener is set up on the "game" element. When a touch
event starts (i.e., a user touches the screen), the event handler function is
triggered.
2. Inside the touchstart event handler function, the changedTouches property of the
event object is used to get information about the first touch point (in this
case, e.changedTouches[0]). The clientX and clientY properties of the touch point
represent the initial touch coordinates, which are stored in startX and startY
3. The touchmove event listener is set up on the "game" element as well. When a
touch event moves (i.e., a user moves their finger on the screen), the event
265
4. Inside the touchmove event handler function, the changedTouches property of
the event object is used again to get information about the touch point that has
moved. The clientX and clientY properties of the touch point represent the current
touch coordinates.
5. The difference between the current touch coordinates and the initial touch
coordinates (diffX and diffY) is calculated to determine how much the ball should
6. The style.left and style.top properties of the "ball" element are updated to change
its position on the screen. The Math.max and Math.min functions are used to limit
the ball's position within the boundaries of the "game" element, so that it doesn't
7. The startX and startY variables are updated with the current touch coordinates,
touch controls.
Note: The "ball" element is assumed to exist in the HTML markup and has an initial
position set using CSS. The code provided only handles the touch events for moving the
ball and does not include any game logic or additional features.
In JavaScript, a Promise is an object that represents the eventual completion (or failure)
of an asynchronous operation and its resulting value. It provides a cleaner and more
266
efficient way to handle asynchronous code compared to traditional callback-based
approaches.
operation is still in progress, and the Promise is neither fulfilled nor rejected.
The Promise has a resulting value associated with it, which can be accessed
rejected explicitly. The Promise has a reason or error associated with it, which
Promises can be used to handle various asynchronous operations such as fetching data
from APIs, making HTTP requests, reading/writing files, and more. Promises can be
chained together using the .then() method, allowing for sequential execution of
asynchronous operations. Additionally, Promises can be combined using methods
like Promise.all() and Promise.race() to handle multiple asynchronous operations
concurrently.
ES6 introduced the async/await syntax, which is built on top of Promises and provides
a more concise way to write asynchronous code. async functions return Promises,
and await is used to pause the execution of an asynchronous function until the Promise
is fulfilled or rejected.
• Error handling: Promises have built-in error handling through the .catch()
267
• Chaining: Promises can be chained together using the .then() method, allowing
applications.
then()
then() is a method available on Promise objects. It is used to attach callbacks or
handlers that will be executed when a Promise is fulfilled, i.e., when the asynchronous
operation associated with the Promise completes successfully.
promise.then(onFulfilled, onRejected);
where promise is the Promise object, onFulfilled is a callback function that will be
executed when the Promise is fulfilled, and onRejected is an optional callback function
that will be executed when the Promise is rejected
The onFulfilled callback function will receive the resolved value of the Promise as its
first argument. If the Promise does not have a resolved value, onFulfilled will receive
undefined. The onRejected callback function, if provided, will receive the reason or error
associated with the rejected Promise as its first argument.
The resolve and reject functions are provided as arguments to the Promise constructor,
and they are used to fulfill or reject the Promise, respectively, when the asynchronous
operation completes.
Example
<!DOCTYPE html>
268
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /
>
<link rel="icon" type="image/ico" href="logo.png" />
<title>Document</title>
<style>
@import url("https://fonts.googleapis.com/css2?family=Lobster&family=
Poppins:wght@100;200;300;400;500;600;700;800&display=swap");
* {
font-family: "Poppins", sans-serif;
}
</style>
</head>
<body>
<h3>Promise in JavaScript</h3>
<button>Click Me</button>
<script src="117_promise.js"></script>
</body>
</html>
script.js
/*
const promise = new Promise((resolve, reject) => {
const sum = 22 + 1;
if (sum == 2) {
resolve("Success");
} else {
reject("Error");
}
});
promise
.then((msg) => {
console.log(msg);
})
269
.catch((error) => {
console.error(error);
});
*/
/*
setTimeout(() => {
console.log("Hi");
}, 250);
function setTimeoutPromise(duration) {
return new Promise((resolve, reject) => {
setTimeout(resolve, duration);
});
}
setTimeoutPromise(250).then(() => {
console.log("Joes");
});
*/
/*
setTimeout(() => {
console.log("Normal : 1");
setTimeout(() => {
console.log("Normal : 2");
setTimeout(() => {
console.log("Normal : 3");
}, 250);
}, 250);
}, 250);
function setTimeoutPromise(duration) {
return new Promise((resolve, reject) => {
setTimeout(resolve, duration);
270
});
}
setTimeoutPromise(250).then(() => {
console.log("Normal SetTime : 1");
setTimeoutPromise(250).then(() => {
console.log("Normal SetTime : 2");
setTimeoutPromise(250).then(() => {
console.log("Normal SetTime : 3");
});
});
});
setTimeoutPromise(250)
.then(() => {
console.log("Cool Promise : 1");
return setTimeoutPromise(250);
})
.then(() => {
console.log("Cool Promise : 2");
return setTimeoutPromise(250);
})
.then(() => {
console.log("Cool Promise : 3");
});
*/
/*
const button = document.querySelector("button");
271
}
*/
/*
console.log(Promise.resolve("Good"));
272
Promise.race([Promise.reject("Good-1"), Promise.resolve("Good-2"), Promise.
resolve("Good-3")])
.then((msg) => {
console.log(msg);
})
.catch((error) => {
console.error(error);
});
Promise.allSettled([Promise.reject("Good-1"), Promise.resolve("Good-2"), Pr
omise.resolve("Good-3")])
.then((msg) => {
console.log(msg);
})
.catch((error) => {
console.error(error);
});
*/
/*
const promise = Promise.reject("Error");
promise
.then((msg) => {
console.log(msg);
})
.catch((err) => {
console.error(err);
})
.finally(() => {
console.log("All Completed..");
});
*/
/*
const getPost = () => {
273
return new Promise((resolve, reject) => {
setTimeout(() => {
const posts = ["Post-1", "Post-2", "Post-3"];
resolve(posts);
}, 1000);
});
};
Promise.all([getPost(), getComments()])
.then((results) => {
//console.log(results);
const [posts, comments] = results;
console.log(`Posts: ${posts}`);
console.log(`Comments: ${comments}`);
})
.catch((err) => {
console.error(err);
});
*/
/*
fetch("https://jsonplaceholder.typicode.com/users")
.then((response) => response.json())
.then((data) => {
console.log(data);
})
.catch((err) => {
274
console.error(err);
});
*/
Normal Functions
function welcome() {
return "Hello World";
}
console.log(welcome());
The provided code defines a function named welcome without any parameters.
Inside the function body, the return statement is used to specify the value that will be
returned when the function is called. In this case, the string "Hello World" is returned.
The console.log() function is used to display the result of calling the welcome function.
By invoking welcome() within the parentheses of console.log() , the function is
executed, and its return value, which is "Hello World" , is printed to the console.
So when you run this code, you will see the output "Hello World" printed in the console.
Async in JavaScript
275
keyword inside its body. It allows you to write code that appears to be synchronous while
actually executing asynchronously.
Example
When the function welcome() is called, it returns a Promise that will resolve with the
value "Hello World". However, in the code provided,
the console.log(welcome()) statement does not directly display the resolved value
because the function is asynchronous.
Instead, the Promise returned by welcome() is logged to the console. This will display
something like Promise {<pending>} indicating that a Promise object is being returned,
but it has not yet been resolved.
Since the function is asynchronous, it will continue executing in the background while
the Promise is pending. The code will not block and wait for the Promise to resolve
before moving on to the next line.
then()
In JavaScript, the then() method is used in conjunction with Promises to handle the
fulfillment or rejection of a Promise and to chain asynchronous operations together.
promise.then(onFulfilled, onRejected);
276
The onFulfilled callback is executed when the Promise is successfully fulfilled
(resolved). It receives the resolved value as an argument. The onRejected callback is
executed when the Promise is rejected, typically when an error occurs during the
asynchronous operation. It receives the reason for the rejection (usually an error object)
as an argument.
If you want to access the resolved value of the Promise, you can use the then() method
to attach a callback function that will be executed when the Promise is fulfilled.
welcome().then((msg) => {
console.log(msg);
})
In this case, the callback function will receive the resolved value "Hello World" as
the msg parameter and log it to the console.
So, in summary, the provided code logs the Promise object returned by
the welcome() function, indicating that it is pending and will eventually resolve with the
value "Hello World". To access and log the resolved value, you need to use
the then() method or await the Promise in an async context.
catch()
In JavaScript, the catch() method is used in conjunction with Promises to handle errors
or rejections that occur during the execution of asynchronous operations. It is specifically
designed to handle the rejected state of a Promise.
When an error occurs within a Promise or the Promise is explicitly rejected using
the reject() function, the catch() method is used to specify a callback function that will
be executed to handle the error.
welcome()
.then((msg) => {
277
console.log(msg);
})
.catch((err) => {
console.error(err);
});
The provided code demonstrates the usage of an async function and the handling of its
returned Promise using then() and catch() methods.
When the welcome() function is called, it returns a Promise that will be immediately
fulfilled with the value "Hello World".
The code console.log(welcome()) logs the Promise object returned by welcome() to the
console. This will display something like Promise {<fulfilled>: "Hello World"}. However,
since the Promise is immediately fulfilled, it doesn't need to wait for any asynchronous
operation to complete.
To access the resolved value of the Promise, the code uses the then() method to attach
a callback function that will be executed when the Promise is fulfilled. In this case, the
callback function receives the resolved value "Hello World" as the msg parameter and
logs it to the console using console.log(msg) .
In the given code, since the Promise is immediately fulfilled, the then() callback is
executed synchronously after the console.log(welcome()) statement. It directly
logs "Hello World" to the console.
The catch() method is also chained after then() to handle any errors that might occur
during the Promise execution. However, since the Promise is immediately fulfilled and
there are no asynchronous operations or rejections happening, the catch() callback will
not be triggered.
In summary, the code logs the Promise object returned by welcome() to the console,
then immediately logs the resolved value "Hello World" using then() . Since there are
no errors or rejections, the catch() callback is not executed in this case.
278
Creating Comments for Blog using Async/Await Function
1. Set up a data structure or a database to store the comments for your blog. This
2. Define an async function, let's say blogComment, to create a new comment for
the blog. This function will receive the necessary data for the comment.
3. Within the blogComment function, you can perform any necessary validation or
4. Use the await keyword to handle asynchronous operations within the function.
5. In case of any errors during the asynchronous operations, use try and catch to
handle and manage the errors gracefully. You can throw custom errors or handle
6. Once the comment has been successfully created, you can return a success
279
});
console.log("Fetching Post....");
let post = await blogPost;
console.log("Post : ", post);
console.log("Fetching Comment....");
let comment = await blogComment;
console.log("Comment : ", comment);
return [post, comment];
}
data
.then((value) => {
console.log(value);
})
.catch((err) => {
console.log(err);
});
This code represents a simplified example of fetching blog post and comment data using
async/await and Promises.
1. The getData() function is defined as an async function. Inside it, two Promises
resolving with the value "Blog Post". Similarly, the blogComment Promise
introduces a delay of 5 seconds before resolving with the value "Comment For
Blog".
280
3. The code then logs "Fetching Post...." to the console, indicating that the process
4. The await keyword is used to pause the execution of the getData() function until
variable post.
5. The code logs the value of the post variable, representing the fetched blog post,
to the console.
variable comment.
8. The code logs the value of the comment variable, representing the fetched blog
9. Finally, the function returns an array [post, comment] containing both the blog
10. Outside the getData() function, "Welcome to Blog Post" is logged to the console.
11. The getData() function is called and assigned to the variable data.
12. The data variable is logged to the console. At this point, it is a pending Promise
because the asynchronous operations inside getData() have not yet completed.
13. The then() method is used to attach a callback function that will be executed
when the data Promise is fulfilled. The resolved value is logged to the console.
14. The catch() method is used to handle any errors that might occur during the
281
delays. The data is fetched sequentially, and the code ensures that the comments are
fetched only after the blog post has been fetched.
Here's a general outline of how you can approach calculating a result asynchronously
using async/await:
logic.
operations and math functions. You can use variables to store intermediate
results.
• If there are any asynchronous operations involved, such as fetching data from an
API or performing database queries, use await to pause the execution until those
Promises.
• Handle any errors that might occur during the asynchronous operations using try-
catch blocks. This allows you to gracefully handle exceptions and provide
282
Here's a simplified example that demonstrates the concept:
/*
90-100 A
80-89 B
70-79 C
<70 D
*/
283
}
resolve(gradeText);
} else {
reject("No Grade");
}
});
};
//then
result([98, 99, 25])
.then((value) => {
console.log("Total : ", value.total);
console.log("Result : ", value.result);
return grade(value);
})
.then((data) => {
console.log(data);
})
.catch((err) => {
console.error(err);
});
284
getResults();
This code demonstrates a scenario where the calculation of a student's result and grade
is performed using Promises and async/await functions in JavaScript.
1. The result function is defined, which takes an array of marks as input. It returns
3. The calculation involves iterating through the marks array, calculating the total,
5. The grade function is defined, which takes the response object from the previous
step as input. It returns a Promise that calculates the grade based on the total.
6. Within the Promise, if the result is "Pass", the average is calculated based on the
8. The code utilizes the then() method to chain the promises together. It calls the
result function with a marks array and logs the total and result to the console.
9. Then, it calls the grade function with the response and logs the grade text.
10. If any errors occur during the promises' execution, they are caught and logged
11. The getResults async function is defined, which performs the same calculation
12. Within the function, the result function is called with a marks array, and the total
285
13. The grade function is called with the response, and the grade text is logged.
14. Any errors that occur during the execution are caught and logged using the try-
catch block.
Overall, this code demonstrates the calculation of a student's result and grade using
Promises and async/await functions. It showcases how the async/await syntax can
provide a more synchronous-like flow when dealing with asynchronous operations and
how Promises can be chained together for handling sequential asynchronous tasks.
The Fetch API is a JavaScript interface that provides a modern and powerful way to
make asynchronous network requests in web browsers. It allows you to fetch resources
from a server, such as JSON data, HTML pages, or binary files, and handle the
response in a flexible manner.
Here are some key features and concepts related to the Fetch API:
• Making Requests: The Fetch API uses the fetch() function to initiate HTTP
requests. You pass in the URL of the resource you want to fetch, along with
The fetch() function returns a Promise that resolves to the response of the
request. You can chain .then() and .catch() methods to handle the response and
286
• Response Handling: Once you have the response, you can use methods
like .json(), .text(), or .blob() to extract the content from the response in different
formats. For example, .json() parses the response as JSON and returns a
• Error Handling: The Fetch API considers network errors, status codes outside
the range of 200-299, and other issues as rejected Promises. You can catch and
meaning you can fetch resources from a different domain or origin. However, you
• Fetch Headers: You can set custom headers in the request to provide additional
The Fetch API is widely supported in modern browsers and is considered a more
modern alternative to older techniques like XMLHttpRequest. It offers a cleaner and
more intuitive syntax for handling asynchronous requests and responses.
It's important to note that the Fetch API uses the underlying network capabilities of the
browser, so it supports the same security considerations as other web-based HTTP
requests. Additionally, since the Fetch API relies on Promises, it can be used effectively
with modern JavaScript features like async/await for more concise and readable code.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
287
<meta name="viewport" content="width=device-width, initial-scale=1.0" /
>
<link rel="icon" type="image/ico" href="logo.png" />
<title>Document</title>
<style>
@import url("https://fonts.googleapis.com/css2?family=Lobster&family=
Poppins:wght@100;200;300;400;500;600;700;800&display=swap");
* {
font-family: "Poppins", sans-serif;
}
.post {
background-color: palegreen;
margin-bottom: 20px;
padding: 20px;
}
.post h4 {
color: blue;
}
</style>
</head>
<body>
<h3>Fetch in JavaScript</h3>
<div id="txt-output">--</div>
<button id="btn-text">Get Text</button>
<hr />
<div id="json-output"></div>
<button id="btn-json">Get Json</button>
<hr />
<script src="fetch_api.js"></script>
288
<hr />
</body>
</html>
fetch_api.js
This code snippet demonstrates different examples of using the Fetch API in JavaScript
to fetch data from various sources, handle the responses, and update the HTML
content. Let's break it down section by section:
btnText.addEventListener("click", getTextFile);
function getTextFile() {
fetch("data.txt")
.then((res) => res.text())
.then((data) => {
outputText.innerHTML = data;
});
}
In this section, there is a button with the ID "btn-text" and an output element with the
ID "txt-output". The getTextFile function is registered as the click event listener for the
button. When the button is clicked, it triggers the function.
Inside getTextFile, the fetch function is used to fetch the "data.txt" file. The response
is received as a Response object, and the .text() method is called on it to extract the
text content of the response. This returns a Promise that resolves to the text data.
In the next .then() block, the text data is received as the data parameter. The HTML
content of the output element is updated with the received data.
btnJson.addEventListener("click", getJsonData);
289
function getJsonData() {
fetch("users.json")
.then((res) => res.json())
.then((users) => {
let data = "<ul>";
users.forEach((user) => {
data += `<li>${user.name} : ${user.age}</li>`;
});
data += "</ul>";
outputJson.innerHTML = data;
});
}
This section is similar to the previous one but fetches a JSON file ("users.json") instead.
The response is parsed as JSON using the .json() method, which returns a Promise that
resolves to the parsed JSON data.
In the subsequent .then() block, the JSON data is received as the users parameter. It
loops over each user and constructs an HTML string to display the user's name and age
in a list (<ul>). The HTML content of the output element is then updated with the
generated data.
btnApi.addEventListener("click", getApiData);
290
});
outputApi.innerHTML = output;
}
In this section, a button with the ID "btn-api" and an output element with the ID "api-
output" are defined. The getApiData function is registered as the click event listener for
the button.
Once the JSON data is received as jsonData, a loop iterates over each post and
constructs an HTML string representing a post's title and body. The generated HTML is
appended to the output variable.
Finally, the HTML content of the output element is updated with the output string,
displaying the posts in a styled format.
Console Output:
console.log("Start");
function hello() {
console.log("Hello World");
}
console.log("end");
console.log("Start");
document.getElementById("btn").addEventListener("click", function callback(
) {
console.log("Hello World");
});
console.log("end");
In this part, console log statements are used to output messages in the browser's
console.
291
The statements console.log("Start"); and console.log("end"); will log the
corresponding messages in the console.
The hello function is defined but not invoked, so it won't log anything unless explicitly
called.
The final block sets up an event listener for a button with the ID "btn". When the button is
clicked, the anonymous callback function logs "Hello World" in the console.
Overall, this code demonstrates fetching data from text files, JSON files, and a remote
API using the Fetch API. The fetched data is then used to update the content of specific
HTML elements. Additionally, there are console log statements to demonstrate logging
messages at different stages of the code execution.
data.txt
This is sample text from data.txt
users.json
The provided data is an array of four objects, each representing information about a
person. Let's break down the structure and the properties of each object:
[
{
"name": "Tiya",
"age": 25,
"gender": "Male",
"contact": 7859586895,
"isMarried": false,
"city": "Salem"
},
{
"name": "Ram",
"age": 32,
"gender": "Male",
"contact": 859658585,
"isMarried": true,
"city": "Chennai"
},
{
292
"name": "Sara",
"age": 18,
"gender": "Female",
"contact": 8596857585,
"isMarried": false,
"city": "Salem"
},
{
"name": "Sam",
"age": 24,
"gender": "Male",
"contact": 856968575,
"isMarried": true,
"city": "Chennai"
}
]
Each object represents a person's information and contains properties such as name,
age, gender, contact number, marital status, and city.
For example, in the first object, "Tiya" is a 25-year-old male from Salem. The isMarried
property is set to false, indicating that Tiya is not married. The contact number is
7859586895.
Similarly, the other objects represent individuals with their respective information.
This data can be useful for various purposes, such as displaying a list of people, filtering
based on certain criteria, or performing data analysis.
293
Here's a step-by-step explanation of how the event loop works in JavaScript:
the execution stack. It keeps track of the currently running function or task.
2. Task Queue: Alongside the execution stack, there is a task queue, also known
as the callback queue or message queue. It holds tasks or events that are ready
language. Events can be triggered by various sources, such as user actions (e.g.,
callback function (also known as an event handler) is generated and placed in the
task queue.
4. Event Loop: The event loop is a continuous process that checks two main
o If the execution stack is empty and there are tasks in the task queue, the
event loop moves the tasks from the task queue to the execution stack,
o The task in the execution stack is processed, and its associated function is
executed.
stack.
294
The event loop repeats the process by checking the execution stack and
6. Non-Blocking Nature: The event loop ensures that JavaScript remains non-
blocking. This means that while asynchronous operations are being performed,
the main thread is free to handle other tasks or respond to user interactions
By leveraging the event loop, JavaScript can efficiently handle concurrency, process
asynchronous operations, and create responsive web applications. Understanding how
the event loop works is crucial for writing efficient and per formant JavaScript code.
The global execution context is a fundamental concept in JavaScript that represents the
environment in which the global JavaScript code is executed. It is created automatically
when a JavaScript program starts running and serves as the initial context for executing
the code.
Here are some key points to understand about the global execution context:
295
1. Creation: When a JavaScript program begins execution, the global execution
context is created. It consists of two main components: the global object and
2. Global Object: The global object serves as the global scope in JavaScript. In a
web browser environment, the global object is typically the window object. It
provides access to various properties and methods that are available globally,
3. Global Scope: The global execution context establishes the global scope, which
any function are placed in the global scope and can be accessed from anywhere
4. this Value: The this value in the global execution context refers to the global
5. Hoisting: During the creation of the global execution context, JavaScript hoists
scopes. This means that regardless of where variables and functions are
declared in the code, they are conceptually moved to the top of the global scope.
executing the code line by line, following the order of statements. As the code
executes, variables are initialized, functions are registered, and executable code
is run.
7. Global Variables and Functions: Variables and functions declared in the global
scope are accessible from any part of the codebase, including nested functions
296
8. Global Execution Context and Function Execution Contexts: Whenever a
function is invoked, a new function execution context is created and added to the
execution stack. These function execution contexts have their own variable
Understanding the global execution context is crucial for comprehending how JavaScript
manages variables, functions, and scope throughout the code execution process. It sets
the foundation for the creation of other execution contexts and plays a vital role in
scoping and variable access within a JavaScript program.
Web APIs (Application Programming Interfaces) are sets of rules and protocols provided
by web browsers to enable web developers to interact with various web browser features
and functionality. These APIs allow developers to access and manipulate web browser
capabilities, interact with web content, handle events, perform network requests, store
and retrieve data, and much more. Web APIs provide a way for web applications to
interact with the underlying browser environment and extend the capabilities of web
development.
setTimeout Function
In JavaScript, the setTimeout() function is a built-in method that allows you to schedule
the execution of a function or the evaluation of an expression after a specified delay. It is
commonly used for adding delays, creating timed animations, implementing timeouts, or
executing code asynchronously.
declaration.
297
• delay: This parameter specifies the time delay (in milliseconds) before the
execution of the callback function. It indicates how long the JavaScript engine
• param1, param2, ...: These optional parameters allow you to pass additional
When setTimeout() is called, it initiates a timer that counts down the specified delay.
Once the delay has elapsed, the JavaScript engine places the callback function in the
event queue, making it ready for execution. The execution of the callback occurs when
the call stack is empty and the event loop checks the event queue.
298
• The first parameter is an anonymous callback function: function callback() {
• The second parameter is the delay specified in milliseconds (5000 in this case).
The important thing to note here is that even though the setTimeout() function is called
before the console.log("end"); statement, the callback function inside setTimeout() is
not executed immediately. Instead, it is scheduled to run after the specified delay. In the
meantime, the code continues executing without waiting for the delay to complete. This
behavior is what allows asynchronous execution in JavaScript.
So, the output shows that "Hello World" is printed after the delay of 5 seconds, following
the "Start" and "end" messages.
The setTimeout() function is a powerful tool for managing delays and executing code
asynchronously in JavaScript. It provides a way to introduce time-based behavior into
your applications and perform actions after a specific duration.
addEventListener Function
• element: This is a reference to the HTML element or object to which you want to
299
• event: The event parameter represents the name of the event you want to listen
custom event.
• callback: The callback function is the function that will be executed when the
additional options for the event listener, such as capturing or once behaviour. It is
When an event occurs on the specified element, the callback function associated with
the event listener is invoked. The callback function typically takes an event object as a
parameter, which contains information about the event, such as the event type, target
element, and other related data.
If you want to see the "Hello World" message being printed, ensure that there is an
HTML element with the id "btn" and simulate a click event on that element. For example,
you can add an HTML button with id="btn" and manually click on it to trigger the event
listener.
300
By utilizing addEventListener(), you can create interactive and responsive web
applications by handling user interactions and other events effectively.
In JavaScript, the Micro Task Queue, also known as the Job Queue or Promise Jobs, is
a component of the JavaScript event loop that handles the execution of micro tasks. It is
a queue that holds tasks that are scheduled to run after the current task but before the
rendering of the UI.
Micro tasks are a category of tasks that have higher priority and are executed
asynchronously. They include tasks such as Promise callbacks (then, catch, finally),
MutationObserver callbacks, and some parts of the ECMAScript specification,
like process.nextTick in Node.js.
1. When a micro task is scheduled for execution, it is added to the Micro Task
Queue.
2. After the current task in the call stack completes, the JavaScript event loop
301
3. If the Micro Task Queue is not empty, the event loop starts executing the tasks
one by one, in the order they were added. Each task is run to completion before
4. While executing the micro tasks, the event loop does not perform any rendering
updates. This means that micro tasks can delay rendering and other visual
5. After all the micro tasks are completed, the event loop checks if there are any
pending rendering updates or other tasks in the task queue. If there are, it
6. This process of alternating between the Micro Task Queue and the Task Queue
The Micro Task Queue has a higher priority compared to the Task Queue, which
contains tasks such as event callbacks (e.g., setTimeout, setInterval) and I/O
operations. The event loop ensures that micro tasks are executed immediately after the
current task, allowing for more fine-grained control over asynchronous operations and
better responsiveness in certain scenarios.
In summary, the Micro Task Queue is a specialized queue in the JavaScript event loop
that handles the execution of micro tasks. It ensures the asynchronous execution of
tasks with higher priority, such as Promise callbacks, before other tasks and rendering
updates take place.
302
Event bubbling is a mechanism in JavaScript where an event triggered on an element is
propagated or "bubbles up" through its parent elements in the DOM hierarchy. It follows
the natural hierarchy of the DOM, starting from the target element and moving up
towards the topmost parent element.
When an event is triggered on an element, such as a click event, it goes through two
phases: capturing and bubbling. In the capturing phase, the event starts from the
topmost parent element (usually the <html> element) and traverses down to the target
element. After the capturing phase, the event enters the bubbling phase, where it
triggers on the target element and then propagates up through its parent elements.
During the bubbling phase, the event triggers on each parent element in the DOM
hierarchy, which means that you can also attach event listeners to the parent or any
ancestor elements to listen for the same event.
Event bubbling is the default behavior in most modern browsers, and it allows for
convenient event handling. It enables you to listen for events on a parent element and
handle events from multiple child elements within it. This approach is particularly useful
when you have a list or a group of elements where you want to apply the same event
handling logic without attaching individual event listeners to each child element.
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /
>
<link rel="stylesheet" href="style.css" />
<link rel="icon" type="image/ico" href="logo.png" />
<title>Document</title>
<style>
div {
303
padding: 30px;
margin: 10px;
border: 3px solid #333;
text-align: center;
}
</style>
</head>
<body>
<h3>Event bubbling | Event Capturing</h3>
<div id="grandparent">
grandparent
<div id="parent">
parent
<div id="child">child</div>
</div>
</div>
<script src="event_bub.js"></script>
</body>
</html>
event_bub.js
This code demonstrates event handling using event bubbling and event capturing
phases in JavaScript. Let's go through the code and understand its behavior.
const grandparent = document.querySelector("#grandparent");
const parent = document.querySelector("#parent");
const child = document.querySelector("#child");
Here, three elements with IDs "grandparent," "parent," and "child" are selected from the
DOM and stored in variables.
grandparent.addEventListener("click", function () {
console.log("Grandparent Clicked");
}, true);
An event listener is attached to the grandparent element with the "click" event. The
listener function logs "Grandparent Clicked" to the console. The third argument, true,
indicates that the listener is registered for the capturing phase.
parent.addEventListener("click", function () {
console.log("Parent Clicked");
304
}, false);
An event listener is attached to the parent element with the "click" event. The listener
function logs "Parent Clicked" to the console. The third argument, false, indicates that
the listener is registered for the bubbling phase.
child.addEventListener("click", function (e) {
console.log("Child Clicked");
e.stopImmediatePropagation();
}, true);
An event listener is attached to the child element with the "click" event. The listener
function logs "Child Clicked" to the console. The third argument, true, indicates that the
listener is registered for the capturing phase.
Additionally, e.stopImmediatePropagation() is called to prevent further propagation of
the event to other elements.
child.addEventListener("click", function (e) {
console.log("Child Clicked2");
}, true);
Another event listener is attached to the child element with the "click" event. The listener
function logs "Child Clicked2" to the console. The third argument, true, indicates that the
listener is registered for the capturing phase.
In this code, event listeners are registered on the grandparent, parent, and child
elements with different capturing/bubbling configurations. By clicking on different
elements, you can observe the order of event execution based on the capturing and
bubbling phases.
Based on the current commented configuration, the order of events logged would be:
305
However, if you uncomment the final configuration
where e.stopImmediatePropagation() is used, only "Child Clicked" will be logged, and
"Child Clicked2" won't be logged due to immediate propagation stoppage.
The behavior of event bubbling and capturing allows you to handle events on different
elements and control the flow of event propagation in the DOM hierarchy.
Example - 2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /
>
<title>Modal</title>
<style>
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@20
0;300;400;500;600;700;900&display=swap");
* {
font-family: "Poppins", sans-serif;
}
#modal {
position: fixed;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
top: 0;
left: 0;
display: none;
align-items: center;
justify-content: center;
}
#modalContent {
background-color: white;
padding: 20px;
border-radius: 5px;
306
}
#modalContent h2 {
font-weight: 600;
}
</style>
</head>
<body>
<button id="btnModal">Open Modal</button>
<div id="modal">
<div id="modalContent">
<h2>Modal Heading</h2>
<p>This is a modal window example.</p>
<input type="text" id="txtName" placeholder="name" />
<button id="btnSubmit">Submit</button>
</div>
</div>
<script>
const btnModal = document.querySelector("#btnModal");
const modal = document.querySelector("#modal");
const btnSubmit = document.querySelector("#btnSubmit");
const txtName = document.querySelector("#txtName");
btnModal.addEventListener("click", function () {
modal.style.display = "flex";
});
modal.addEventListener("click", function () {
modal.style.display = "none";
});
307
});
</script>
</body>
</html>
This code demonstrates a simple modal behavior with event handling in JavaScript.
Let's go through the code and understand its functionality.
const btnModal = document.querySelector("#btnModal");
const modal = document.querySelector("#modal");
const btnSubmit = document.querySelector("#btnSubmit");
const txtName = document.querySelector("#txtName");
Here, elements with IDs "btnModal," "modal," "btnSubmit," and "txtName" are selected
from the DOM and stored in variables.
btnModal.addEventListener("click", function () {
modal.style.display = "flex";
});
An event listener is attached to the btnModal element with the "click" event. When the
button is clicked, the listener function is triggered, and it sets the display property of the
modal element to "flex", making the modal visible.
modal.addEventListener("click", function () {
modal.style.display = "none";
});
An event listener is attached to the modal element with the "click" event. When the
modal is clicked, the listener function is triggered, and it sets the display property of the
modal element to "none", hiding the modal.
btnSubmit.addEventListener("click", function (e) {
e.stopPropagation();
console.log("Submit button Pressed");
});
An event listener is attached to the btnSubmit element with the "click" event. When the
submit button is clicked, the listener function is triggered, and it logs "Submit button
Pressed" to the console. Additionally, e.stopPropagation() is called to prevent further
propagation of the event, ensuring that the modal doesn't close when clicking on the
submit button.
txtName.addEventListener("click", function (e) {
308
e.stopPropagation();
console.log("Input Click");
});
An event listener is attached to the txtName element with the "click" event. When the
input field is clicked, the listener function is triggered, and it logs "Input Click" to the
console. Similarly, e.stopPropagation() is called to prevent further propagation of the
event.
In summary, this code sets up a modal behavior where clicking the "Open
Modal" button displays the modal, and clicking anywhere outside the modal closes it.
The submit button and input field inside the modal have event listeners
with e.stopPropagation() to prevent the modal from closing when interacting with them.
The code showcases how event handling can be used to control the behavior of a modal
and capture specific actions within the modal without affecting the overall modal
functionality.
Event delegation is a technique in JavaScript that allows you to handle events on parent
elements rather than directly attaching event listeners to individual child elements. With
event delegation, you can efficiently manage events for dynamically added or removed
elements within a container.
The concept behind event delegation is based on event propagation, which includes two
phases: capturing and bubbling. When an event occurs on a DOM element, it first goes
through the capturing phase, where the event is triggered on the parent elements
starting from the top of the DOM hierarchy and moving towards the target element. After
the capturing phase, the event enters the bubbling phase, where it triggers on the target
element and then propagates up through the parent elements.
309
Event delegation takes advantage of event bubbling. Instead of attaching an event
listener to each individual child element, you attach a single event listener to the parent
element. When an event occurs on a child element, it bubbles up to the parent element
and triggers the event listener attached to the parent. The parent element then
determines which child element triggered the event by inspecting
the event.target property.
The main advantages of event delegation are:
1. Efficiency: With event delegation, you can handle events for a large number of
elements efficiently, as you only need to attach a single event listener on the
parent element rather than multiple listeners on each child element. This is
dynamically added or removed elements without the need to attach and detach
event listeners manually. The parent element remains constant, so it can handle
3. Simplified Code: By using event delegation, you can write cleaner and more
concise code by avoiding the need to attach event listeners to each individual
element. This leads to better code maintainability and reduces the chances of
Example - 1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /
>
<title>Event Delegation</title>
<link rel="stylesheet" href="style.css" />
</head>
310
<body>
<div class="container">
<h3>Event Delegation in JavaScript</h3>
<div id="categories">
<div class="product" id="Laptops">Laptops</div>
<div class="product" id="cameras">Cameras</div>
<div class="product" id="printer">Printer</div>
<div class="product" id="tv">TV</div>
<div class="product" id="ac">AC</div>
<div class="product" id="mobiles">Mobiles</div>
</div>
</div>
<script src="delegation.js"></script>
</body>
</html>
style.css
@import url("https://fonts.googleapis.com/css2?family=Lobster&family=Poppin
s:wght@100;200;300;400;500;600;700;800&display=swap");
* {
font-family: "Poppins", sans-serif;
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
width: 100vw;
height: 100vh;
display: grid;
place-items: center;
}
.container {
width: 650px;
background-color: #333;
padding: 10px;
311
}
h3 {
font-weight: 300;
font-size: 25px;
margin: 10px 5px;
color: #fff;
text-align: center;
}
#categories {
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.product {
width: 150px;
height: 150px;
background-color: palegreen;
text-align: center;
line-height: 150px;
color: brown;
font-weight: 400;
font-size: 18px;
cursor: pointer;
}
delegation.js
const catagories = document.getElementById("categories");
312
});
This code snippet demonstrates an event listener that handles a click event on an
element with the ID "categories". Let's break it down step by step:
This line fetches the DOM element with the ID "categories" and assigns it to the variable
catagories. It assumes there is an HTML element with the ID "categories" in the
document.
Inside the event handler, this if statement checks if the element that triggered the click
event has a CSS class name equal to "product". This is done by accessing
the className property of the e.target element, which represents the actual element
that was clicked.
If the condition is true, it means the clicked element has the class "product", and the
code inside the if block will be executed.
This line sets the window.location.href property to a new URL. It concatenates "/" with
the id property of the clicked element (e.target.id). The resulting URL will navigate the
user to a new page, using the value of the clicked element's ID as part of the URL path.
313
In summary, this code listens for click events on the "categories" element. If the clicked
element has the class "product", it retrieves its ID and redirects the user to a new page
using that ID as part of the URL path.
Example - 2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /
>
<title>Document</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<form action="#" id="frm">
<div class="form-group">
<label for="firstName">First Name</label>
<input type="text" placeholder="Enter First Name" data-uppercase />
</div>
<div class="form-group">
<label for="lastName">Last Name</label>
<input type="text" placeholder="Enter Last Name" data-uppercase />
</div>
</form>
<script src="script.js"></script>
</body>
</html>
style.css
@import url("https://fonts.googleapis.com/css2?family=Lobster&family=Poppin
s:wght@100;200;300;400;500;600;700;800&display=swap");
* {
font-family: "Poppins", sans-serif;
margin: 0;
padding: 0;
314
box-sizing: border-box;
}
body {
width: 100vw;
height: 100vh;
display: grid;
place-items: center;
background-color: aliceblue;
}
#frm {
width: 650px;
background-color: #fff;
padding: 10px;
display: flex;
flex-direction: column;
gap: 10px;
}
.form-group {
display: flex;
flex-direction: column;
margin-bottom: 10px;
}
.form-group label {
margin-bottom: 5px;
}
.form-group input {
border: 1px solid #ccc;
padding: 5px 10px;
border-radius: 3px;
outline: none;
}
315
script.js
const frm = document.getElementById("frm");
This code snippet demonstrates an event listener that handles the "keyup" event on a
form element with the ID "frm". Here's a breakdown of how it works:
This line fetches the form element with the ID "frm" from the DOM and assigns it to the
variable frm. It assumes there is an HTML form element with the ID "frm" in the
document.
The provided arrow function (e) => {...} is the event handler that will be executed when
the keyup event occurs. The e parameter represents the event object, which contains
information about the event.
if (e.target.dataset.uppercase != undefined) {
e.target.value = e.target.value.toUpperCase();
}
Inside the event handler, this if statement checks if the element that triggered the keyup
event has a "data-uppercase" attribute. It uses the dataset property of the e.target
element to access custom data attributes.
If the condition is true, it means the element has the "data-uppercase" attribute,
indicating that the value entered in the form element should be converted to uppercase.
316
In that case, the line e.target.value = e.target.value.toUpperCase(); sets the value of
the form element to its uppercase version.
In summary, this code listens for keyup events within the "frm" form element. If the
element has a "data-uppercase" attribute, it automatically converts the entered value
to uppercase. This functionality can be useful for enforcing uppercase input in specific
form fields.
To implement event delegation, you attach an event listener to the parent element and
use conditional statements to determine which child element triggered the event based
on the event.target. You can then perform the desired actions or event handling logic
accordingly.
Event delegation is commonly used in scenarios where you have a list or a container
with multiple elements that require similar event handling, such as a dynamic list of
items, a table, or a menu. It provides a scalable and efficient approach to handling
events in these situations.
317
In JavaScript, a debounce function makes sure that your code is only triggered once per
user input. Search box suggestions, text-field auto-saves, and eliminating double-button
clicks are all use cases for debounce.
1. func: is a function that you want to execute after the debounce time
2. timeout: The amount of time you want the debounce function to wait after the
sample Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /
>
<title>Debouncing in Javascript</title>
</head>
<body>
<h5>Debouncing in Javascript</h5>
<input type="text" id="txtInput" />
<script src="script.js"></script>
</body>
</html>
script.js
const txtInput = document.getElementById("txtInput");
txtInput.addEventListener("keyup", function () {
318
optimizeFunction();
});
let counter = 0;
const getDataFromApi = () => {
console.log("Getting Data....", counter++);
};
Local Storage in JavaScript refers to a web browser feature that allows web applications
to store data persistently on a user's device. It provides a simple key-value store where
developers can save and retrieve data directly within the user's browser. Local Storage
is often used to store user preferences, settings, or any data that should be available
between sessions or page refreshes without the need for a server.
319
Local Storage in JavaScript refers to a web browser feature that allows web applications
to store data persistently on a user's device. It provides a simple key-value store where
developers can save and retrieve data directly within the user's browser. Local Storage
is often used to store user preferences, settings, or any data that should be available
between sessions or page refreshes without the need for a server.
Data FormatData stored in Local Storage is always in the form of key-value pairs. Both
the keys and values are stored as strings. If you need to store more complex data
structures, you'll need to serialize and deserialize them, typically using JSON.
Persistent Storage Unlike session storage, data stored in Local Storage persists even
after the browser is closed or the user navigates away from the page. It remains
available until explicitly removed by the user, cleared by the application, or until it
expires.
Same-Origin Policy Local Storage follows the same-origin policy, which means that a
web page can only access data stored in Local Storage by the same domain. This
restriction enhances security by preventing one website from accessing another
website's data.
Simple API : Local Storage provides a straightforward API for working with data:
value.
• localStorage.clear(): Clears all data stored in Local Storage for the current
domain.
Events : Local Storage also provides events that notify you when data
changes:storage event: Fired on a different window or tab when data is changed in
320
Local Storage. This can be used to synchronize data between different browser
instances.
sample Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /
>
<title>LocalStorage Array Values</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<h1>CRUD with Local Storage</h1>
<p>1.convert Array to strings using <mark>JSON.stringify()</mark> bef
ore storing</p>
<p>2.convert them back to their original form using <mark>JSON.parse(
)</mark> after retrieving.</p>
<hr />
<form id="dataForm">
<label for="dataInput">Enter Data</label>
<input type="text" id="dataInput" />
<button type="submit">Add Data</button>
</form>
<div id="output">
<h2>Stored Data</h2>
<ul id="dataList"></ul>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
<form> Element:
321
• The <form> element is used to create an HTML form that can be used to collect
<label> Element:
• The <label> element is used to provide a text label for an input field. It helps
• for="dataInput": The for attribute is used to associate the label with a specific
input element. In this case, it is associated with the input element with
<input> Element:
• The <input> element is an empty element used for various types of user input.
• type="text": This specifies that the input field is a text input where users can
identifier, "dataInput," to the input element. It can be used to reference this input
<button> Element:
• The <button> element creates a clickable button that users can interact with.
• type="text": This specifies that the input field is a text input where users can
• type="submit": This attribute specifies that this button is a submit button, which
means that when clicked, it will trigger the form to be submitted. Typically, this
322
script.js
document.addEventListener("DOMContentLoaded", function () {
const dataForm = document.getElementById("dataForm");
const dataInput = document.getElementById("dataInput");
const dataList = document.getElementById("dataList");
loadStoredData();
function addToLocalStorage(data) {
const storedData = JSON.parse(localStorage.getItem("myData")) || [];
storedData.push(data);
localStorage.setItem("myData", JSON.stringify(storedData));
}
323
dataList.appendChild(li);
*/
let output = `
<li>
${data}
<div>
<button class='btnEdit' data-index='${index}' >Edit</button>
<button class='btnDelete'data-index='${index}' >Delete</button>
</div>
<li>
`;
dataList.innerHTML += output;
});
324
const index = this.dataset.index;
const storedData = JSON.parse(localStorage.getItem("myData")) || [];
const newData = prompt("Edit Username", storedData[index]);
if (newData !== null) {
storedData[index] = newData.trim();
localStorage.setItem("myData", JSON.stringify(storedData));
loadStoredData();
}
}
});
The code begins by adding an event listener for the "DOMContentLoaded" event,
ensuring that the JavaScript code only runs after the HTML document has been fully
loaded.
The loadStoredData function is called to load any existing data from Local Storage and
display it in the "dataList" element.
An event listener is set up for the form's "submit" event. When the user submits the form,
the callback function:
• Retrieves the value entered in the input field, trims any leading or trailing
• If the input is not empty, it calls the addToLocalStorage function to store the data
in Local Storage, reloads the stored data using loadStoredData, and clears the
input field.
• If the input is empty, it displays an alert and focuses on the input field.
325
The addToLocalStorage function is responsible for adding new data to Local Storage. It
retrieves the existing data, adds the new data, and updates Local Storage.
The loadStoredData function retrieves data from Local Storage, iterates over it, and
dynamically generates list items with associated delete and edit buttons for each data
item. Event listeners for delete and edit actions are added to these buttons.
The deleteData function allows users to delete a data item. It prompts for confirmation
and then removes the selected data item from Local Storage. After deletion, it
calls loadStoredData to refresh the data list.
The editData function enables users to modify an existing data item. It prompts for the
new data, updates the item in Local Storage, and then refreshes the data list with the
updated data using loadStoredData.
Overall, this code provides a simple user interface for adding, viewing, editing, and
deleting data items stored in Local Storage within a web page.
To enhance the user experience, it's essential to add CSS styles to the HTML page for a
visually appealing and organized presentation of content.
style.css
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;
500;600;700&display=swap");
* {
margin: 0;
padding: 0;
}
body {
font-family: "Poppins", sans-serif;
background-color: #f0f0f0;
}
.container {
max-width: 800px;
background-color: #fff;
margin: 0 auto;
padding: 20px;
326
border: 1px solid #ccc;
border-radius: 5px;
}
h1 {
text-align: center;
font-weight: 500;
font-size: 18px;
color: crimson;
text-transform: uppercase;
margin-bottom: 10px;
}
p {
margin-bottom: 10px;
}
hr {
margin-top: 20px;
margin-bottom: 20px;
}
mark {
font-weight: bold;
}
h2 {
font-size: 16px;
font-weight: 500;
color: chocolate;
margin-bottom: 10px;
}
label,
input {
display: block;
margin-bottom: 5px;
}
button {
padding: 3px 6px;
327
}
#output {
border-top: 1px solid #ccc;
padding-top: 10px;
margin-top: 10px;
}
#dataList {
list-style-type: none;
}
#dataList li {
display: flex;
justify-content: space-between;
margin-bottom: 5px;
}
328
Object Local Storage" in JavaScript typically refers to the practice of storing JavaScript
objects (complex data structures) in Local Storage, a web browser feature that allows
data to be stored persistently on a user's device. This approach involves serializing
JavaScript objects to JSON strings before storing them in Local Storage and
deserializing them when retrieved.
Local Storage:
Local Storage is a web browser feature that allows web applications to store data on the
user's device. It provides a simple key-value store for storing data persistently between
browser sessions.
JavaScript Objects:
JavaScript objects are complex data structures that can hold various types of data,
including nested objects, arrays, strings, numbers, and more. They are often used to
represent structured data in web applications.
Object Serialization:
To store JavaScript objects in Local Storage, they must be converted (serialized) into a
format that Local Storage can handle. Typically, objects are serialized to JSON
(JavaScript Object Notation), which is a text-based format that can represent complex
data structures.
JSON.stringify():
JSON Parsing:
When retrieving data from Local Storage, the stored JSON string needs to be converted
back into a JavaScript object. This process is called deserialization.
JSON.parse():
sample Code
<!DOCTYPE html>
329
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /
>
<title>Object-LocalStorage</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<h1>CRUD with Local Storage</h1>
<form id="dataForm">
<label for="nameInput">Name:</label>
<input type="text" id="nameInput" required />
<label for="ageInput">Age:</label>
<input type="number" id="ageInput" required />
<label for="genderSelect">Gender:</label>
<select id="genderSelect" required>
<option value="">Select Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<div id="output">
<h2>Stored Data:</h2>
<table id="dataTable">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
<th>Edit</th>
330
<th>Delete</th>
</tr>
</thead>
<tbody id="dataList"></tbody>
</table>
</div>
</div>
<div class="modal">
<div class="modal-content">
<span class="close">×</span>
<h2>Edit Data</h2>
<form id="editForm">
<input type="hidden" id="editIndex" />
<label for="editNameInput">Name:</label>
<input type="text" id="editNameInput" required />
<label for="editAgeInput">Age:</label>
<input type="number" id="editAgeInput" required />
<label for="editGenderSelect">Gender:</label>
<select id="editGenderSelect" required>
<option value="">Select Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
script.js
document.addEventListener("DOMContentLoaded", function () {
const modal = document.querySelector(".modal");
331
const closeBtn = document.querySelector(".close");
const tableBody = document.querySelector("#dataList");
const dataForm = document.getElementById("dataForm");
332
const newAge = parseInt(editAgeInput.value);
const newGender = editGenderSelect.value;
if (newName !== "" && !isNaN(newAge) && newGender !== "") {
const storedData = JSON.parse(localStorage.getItem("myData")) || [];
storedData[index].name = newName;
storedData[index].age = newAge;
storedData[index].gender = newGender;
localStorage.setItem("myData", JSON.stringify(storedData));
editForm.reset();
modal.style.display = "none";
loadStoredData();
} else {
alert("Please Fill All Details");
}
});
function addToLocalStorage(user) {
const storedData = JSON.parse(localStorage.getItem("myData")) || [];
storedData.push(user);
localStorage.setItem("myData", JSON.stringify(storedData));
}
loadStoredData();
function editData() {
const index = this.dataset.index;
const storedData = JSON.parse(localStorage.getItem("myData")) || [];
const data = storedData[index];
editIndex.value = index;
editNameInput.value = data.name;
editAgeInput.value = data.age;
editGenderSelect.value = data.gender;
modal.style.display = "block";
}
function deletaData() {
if (confirm("Are You Sure to Delete ?")) {
333
const index = this.dataset.index;
const storedData = JSON.parse(localStorage.getItem("myData")) || [];
storedData.splice(index, 1);
localStorage.setItem("myData", JSON.stringify(storedData));
loadStoredData();
}
}
// Function to close the modal using Close Btn
closeBtn.addEventListener("click", function () {
modal.style.display = "none";
});
function loadStoredData() {
const storedData = JSON.parse(localStorage.getItem("myData")) || [];
tableBody.innerHTML = "";
storedData.forEach(function (data, index) {
const row = document.createElement("tr");
row.innerHTML = `
<td>${data.name}</td>
<td>${data.age}</td>
<td>${data.gender}</td>
<td><button data-index="${index}" class="btnEdit">Edit</button></td
>
<td><button data-index="${index}" class="btnDelete">Delete</button>
</td>
`;
tableBody.appendChild(row);
});
const editButtons = document.querySelectorAll(".btnEdit");
editButtons.forEach((btn) => {
btn.addEventListener("click", editData);
334
});
/*
[{"name":"Tiya","age":2,"gender":"Female"},{"name":"Raja","age":45,"gender"
:"Male"}]
*/
The code starts by adding an event listener for the "DOMContentLoaded" event,
ensuring that the JavaScript code only runs after the HTML document has been fully
loaded.
DOM elements are selected and stored in variables. These elements include the modal
dialog, form elements, input fields for adding data, and input fields for editing data.
Event listeners are set up for the form submissions. The dataForm listener handles
adding new data, while the editForm listener handles editing existing data. Both forms
prevent the default form submission behavior using e.preventDefault().
The addToLocalStorage function is responsible for adding new data to Local Storage. It
retrieves existing data, pushes the new user data, and updates Local Storage.
The loadStoredData function loads and displays stored data from Local Storage. It
dynamically generates table rows for each data item and adds event listeners to edit and
delete buttons.
The editData function allows users to edit existing data. It populates the edit form with
the selected data and opens the modal dialog for editing.
The deletaData function enables users to delete data items. It prompts for confirmation
and removes the selected data item from Local Storage.
Event listeners are added for closing the modal dialog using both the "Close" button and
by clicking outside of the modal window.
335
Finally, the code initializes by calling loadStoredData() to load and display any existing
data stored in Local Storage.
To enhance the user experience, it's essential to add CSS styles to the HTML page for a
visually appealing and organized presentation of content.
style.css
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;
500;600;700&display=swap");
* {
margin: 0;
padding: 0;
}
body {
font-family: "Poppins", sans-serif;
background-color: #f0f0f0;
}
.container {
max-width: 500px;
background-color: #fff;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
h1 {
text-align: center;
font-weight: 500;
font-size: 18px;
color: crimson;
text-transform: uppercase;
margin-bottom: 10px;
}
h2 {
336
font-size: 16px;
font-weight: 500;
color: chocolate;
margin-bottom: 10px;
}
label,
input,
select {
display: block;
width: 250px;
height: 25px;
margin-bottom: 5px;
padding-left: 2px;
}
button {
display: block;
padding: 3px 15px;
}
#output {
margin-top: 30px;
border-top: 1px solid #ccc;
padding-top: 10px;
}
table {
width: 100%;
border-collapse: collapse;
}
th,
td {
padding: 5px 3px;
text-align: left;
border-bottom: 1px solid #ddd;
}
337
tr:hover {
background-color: #f2f2f2;
}
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
}
.modal-content {
background-color: #fff;
width: 60%;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
}
.close {
float: right;
font-size: 28px;
font-weight: bold;
cursor: pointer;
color: #aaa;
}
.close:hover {
color: black;
}
#editForm button,
338
#dataForm button {
margin-top: 10px;
}
Object Local Storage is commonly used when you need to persistently store and retrieve
structured data, such as user preferences, configuration settings, or application state.
However, keep in mind that Local Storage has limitations, including a storage size limit
and being restricted to the same-origin policy. Additionally, it's important to ensure that
the data you store in Local Storage does not contain sensitive information since it's
accessible to JavaScript running on the same domain.
Changing template colors in JavaScript refers to the ability to dynamically modify the
color scheme of a web page or application using JavaScript. This is a common feature in
web development that allows users to personalize the visual appearance of a website or
web app to suit their preferences.
CSS Variables or Classes : There are two common approaches to implementing color
customization:
339
JavaScript can then change the values of these variables, which will
• CSS Classes: You can define CSS classes for different color schemes, and
JavaScript can toggle or switch between these classes to apply different color
styles.
Event Handling : Event listeners are used to detect user interactions with color
customization UI elements. When a user selects a color or theme, JavaScript captures
this interaction and updates the styles accordingly.
Storing User Preference : To ensure that users' color preferences are remembered
between visits or page reloads, you may store their choices in a user's browser, often
using techniques like Local Storage or cookies.
To enhance the user experience, it's essential to add CSS styles to the HTML page for a
visually appealing and organized presentation of content.
sample Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /
>
<title>Dark Light</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="banner" id="banner">
<h1 class="title">Welcome to Tutor Joe's</h1>
<p class="slogan">Discover the possibilities</p>
<button id="theme-toggle">Toggle Theme</button>
</div>
340
<script src="script.js"></script>
</body>
</html>
• The <div> element is a generic container used to group and structure content on
a web page.
and a unique identifier ("banner") to the <div>. CSS classes and IDs are
commonly used to style and select elements using CSS and JavaScript.
<h1> Element
• class="title": This attribute assigns a CSS class ("title") to the <h1>. It can be
<p> Element:
• class="slogan": This attribute assigns a CSS class ("slogan") to the <p>. Like the
<button> Element:
the button, which can be used to select the button using JavaScript.
Text Content
• Inside the <h1> element, you have the text "Welcome to Tutor Joe's," which is
341
• Inside the <p> element, you have the text "Discover the possibilities," which
• Inside the <button> element, you have the text "Toggle Theme," which
Overall, this HTML code represents a banner section at the top of a webpage. It includes
a title, a slogan, and a button that can be used to toggle between different themes or
perform some other action when clicked. To implement theme toggling or any other
interactivity, you would typically use JavaScript and CSS in conjunction with this HTML
structure.
script.js
const btnToggle = document.getElementById("theme-toggle");
function toggleTheme() {
const banner = document.getElementById("banner");
banner.classList.toggle("dark");
btnToggle.addEventListener("click", toggleTheme);
window.addEventListener("DOMContentLoaded", function () {
const themePreference = localStorage.getItem("themePreference");
if (themePreference === "dark") {
const banner = document.getElementById("banner");
banner.classList.add("dark");
}
});
This JavaScript code provides functionality to toggle between a light and dark theme for
a webpage using a button click and to remember the user's theme preference using
Local Storage.
342
const btnToggle = document.getElementById("theme-toggle");: This line selects the
button with the id "theme-toggle" and assigns it to the btnToggle variable. This button is
used to toggle the theme.
function toggleTheme() { ... }: This is a function that handles toggling between the light
and dark themes. It does the following:
• It selects the element with the id "banner," which is assumed to be the container
• It uses the classList.toggle() method to toggle the "dark" class on the "banner"
using localStorage.setItem().
localStorage.getItem().
• It checks if the user prefers a dark theme. If the user previously selected a dark
theme, it adds the "dark" class to the "banner" element to apply the dark theme
Overall, this code provides a simple mechanism to allow users to toggle between light
and dark themes on a webpage and remembers their preference across page visits
using Local Storage.
343
style.css
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;
500;600;700&display=swap");
* {
font-family: "Poppins", sans-serif;
}
.banner {
background-color: #f1e9e9;
color: #446456;
padding: 20px;
}
.title {
font-size: 28px;
font-weight: 500;
margin: 0;
}
.slogan {
font-size: 18px;
}
.dark {
background-color: #333333;
color: #ffffff;
}
Session Storage is a web storage mechanism available in JavaScript that allows you to
store key-value pairs of data on the client side, similar to cookies and local storage.
However, unlike cookies, session storage is temporary and has a limited scope.
344
Temporary Storage : Data stored in session storage is only available for the duration of
a page session. A session typically lasts as long as the user has the web page open and
ends when the user closes the tab or browser. This makes session storage useful for
temporarily storing data that you only need while the user is interacting with your
website.
Data Persistence : Unlike local storage, session storage data is not persistent across
browser sessions. It will be automatically cleared when the user closes the browser tab
or window.
Scope : Unlike local storage, session storage data is not persistent across browser
sessions. It will be automatically cleared when the user closes the browser tab or
window.
Simple API : Session storage provides a simple API to store and retrieve data. You can
use the sessionStorage object in JavaScript to set and get data using key-value pairs.
Data Types : Session storage can store various data types, including strings, numbers,
objects, and arrays. The data is automatically serialized to strings when stored and
deserialized when retrieved.
Storage Limitations : Like other web storage mechanisms, session storage has
limitations on the amount of data you can store. It typically allows for more storage
space (usually around 5-10 MB) compared to cookies but less than local storage.
No Expiry : Data stored in session storage does not have an expiration date. It will
remain available until the end of the session or until explicitly removed.
sample Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /
>
<title>Step-1</title>
345
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<h1>Multi-Step Form Session Storage</h1>
<h2>Step 1 - Personal Details</h2>
<form>
<label for="name">Name</label>
<input type="text" id="name" placeholder="Enter Full Name" />
<label for="email">Email:</label>
<input type="email" id="email" placeholder="Enter Email Address" />
<button type="button" id="btnStep1Next">Next Step</button>
</form>
</div>
<script>
const name = document.getElementById("name");
const email = document.getElementById("email");
const btnStep1Next = document.getElementById("btnStep1Next");
function loadSession() {
let data = sessionStorage.getItem("formData") || {};
if (data.length > 0) {
data = JSON.parse(data);
name.value = data.name;
email.value = data.email;
}
}
loadSession();
btnStep1Next.addEventListener("click", function () {
if (name.value != "" && email.value != "") {
const formData = JSON.parse(sessionStorage.getItem("formData")) |
| {};
formData.name = name.value;
formData.email = email.value;
sessionStorage.setItem("formData", JSON.stringify(formData));
346
window.location.href = "http://127.0.0.1:5500/step2.html";
} else {
alert("Please Fill All Details");
name.focus();
}
});
</script>
</body>
</html>
the <body>.
2. It starts by selecting and storing references to the "Name" input field (name), the
"Email" input field (email), and the "Next Step" button (btnStep1Next) in
variables.
3. loadSession() Function:
and populate the form fields with any previously entered data. It is called
be a JSON string.
o If there is data in session storage, it parses the JSON data and populates
the "Name" and "Email" input fields with the saved values.
347
o When the button is clicked, the code checks if both the "Name" and
session storage, adds the "Name" and "Email" values to it, and then
assuming that this is the URL for the next step of the multi-step form.
5. Data Validation
Before storing data in session storage, the code checks if the "Name" and "Email"
fields are filled out. If not, it displays an alert to prompt the user to fill in all the
details and focuses on the "Name" field.
step2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /
>
<title>Step-2</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<h1>Multi-Step Form Session Storage</h1>
<h2>Step 2 - Additional Details</h2>
<form>
<label for="address">Address:</label>
<input type="text" id="address" placeholder="Full Address" />
<label for="phone">Phone:</label>
<input type="text" id="phone" placeholder="Enter Contact Number" />
348
<button type="button" id="btnStep1Back">Back Step</button>
<button type="button" id="btnStep2Next">Next Step</button>
</form>
</div>
<script>
const address = document.getElementById("address");
const phone = document.getElementById("phone");
const btnStep1Back = document.getElementById("btnStep1Back");
const btnStep2Next = document.getElementById("btnStep2Next");
function loadSession() {
let data = sessionStorage.getItem("formData") || {};
if (data.length > 0) {
data = JSON.parse(data);
address.value = data.address == undefined ? "" : data.address;
phone.value = data.phone == undefined ? "" : data.phone;
}
}
loadSession();
btnStep1Back.addEventListener("click", function () {
window.location.href = "http://127.0.0.1:5500/index.html";
});
btnStep2Next.addEventListener("click", function () {
if (address.value != "" && phone.value != "") {
const formData = JSON.parse(sessionStorage.getItem("formData")) |
| {};
formData.address = address.value;
formData.phone = phone.value;
sessionStorage.setItem("formData", JSON.stringify(formData));
window.location.href = "http://127.0.0.1:5500/review.html";
} else {
alert("Please Fill All Details");
349
address.focus();
}
});
</script>
</body>
</html>
1. loadSession() Function:
session storage.
be a JSON string.
Next, it constructs an HTML table (inside the output variable) with rows
for "Name," "Email," "Address," and "Contact No" and populates the
2. loadSession() Execution
ensuring that the user's entered data is displayed when the page loads.
In summary, this code represents the "Review" step of a multi-step form. It retrieves
user-entered data from session storage, displays it in a tabular format, and provides a
"Back Step" button to allow the user to return to the previous step if needed. Additionally,
there is a "Confirm Submission" button, which appears to be intended for the user to
350
confirm their form submission, but its functionality is not implemented in the provided
code.
review.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /
>
<title>Review</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<h1>Multi-Step Form Session Storage</h1>
<h2>Review Details</h2>
<table id="dataTable"></table>
function loadSession() {
let data = sessionStorage.getItem("formData") || {};
data = JSON.parse(data);
let output = "";
output = `
<tr>
<th>Name</th>
351
<td>${data.name}</td>
</tr>
<tr>
<th>Email</th>
<td>${data.email}</td>
</tr>
<tr>
<th>Address</th>
<td>${data.address}</td>
</tr>
<tr>
<th>Contact No</th>
<td>${data.phone}</td>
</tr>`;
dataTable.innerHTML = output;
}
loadSession();
</script>
</body>
</html>
1. loadSession() Function
session storage.
be a JSON string.
o The code then parses the JSON data into a JavaScript object.
with rows for "Name," "Email," "Address," and "Contact No" and populates
352
o Finally, it sets the innerHTML of the "dataTable" table element to the
format.
2. loadSession() Execution:
ensuring that the user's entered data is displayed when the page loads.
In summary, this code represents the "Review" step of a multi-step form. It retrieves
user-entered data from session storage, displays it in a table, and provides a "Back
Step" button for users to navigate to the previous step. However, the "Confirm
Submission" button is included in the HTML but does not have its functionality
implemented in the provided code.
To enhance the user experience, it's essential to add CSS styles to the HTML page for a
visually appealing and organized presentation of content.
style.css
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;
500;600&display=swap");
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
body {
background-color: #f2f2f2;
width: 100vw;
height: 100vh;
display: grid;
place-items: center;
}
353
.container {
width: 600px;
background-color: #fff;
border: 1px solid #ccc;
padding: 20px;
border-radius: 5px;
}
h1 {
font-size: 20px;
font-weight: 500;
margin-bottom: 20px;
text-align: center;
text-transform: uppercase;
}
h2 {
font-size: 18px;
font-weight: 500;
margin-bottom: 15px;
color: chocolate;
text-transform: uppercase;
}
label {
display: block;
margin-bottom: 10px;
}
input[type="text"],
input[type="email"] {
width: 100%;
padding: 10px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 5px;
margin-bottom: 20px;
354
}
button {
padding: 10px 20px;
font-size: 16px;
background-color: #4caf50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
}
button:hover {
background-color: #45a049;
}
table {
width: 100%;
border: 1px solid #ccc;
margin-bottom: 15px;
border-collapse: collapse;
}
table th,
table td {
border-bottom: 1px solid #ccc;
padding: 10px;
text-align: left;
cursor: pointer;
}
table td {
border-left: 1px solid #ccc;
}
tr:hover {
355
background-color: #f1f1f1;
}
.finish {
background-color: #fa5828;
}
.finish:hover {
background-color: #bd3309;
}
Session storage is commonly used for storing temporary user preferences, maintaining
user login status during a session, and caching data needed for the current user
interaction. It provides a convenient way to work with client-side data without the need
for server interactions.
356