Mastering DOM Manipulation Techniques
Mastering DOM Manipulation Techniques
Accessing Elements:
Selecting Elements by ID:
You can select elements with a specific ID using [Link]().
Selecting Elements by Class:
To select elements by class name, use [Link]().
Selecting Elements by Tag Name:
To select elements by their HTML tag, use [Link]().
Selecting Elements by CSS Selectors:
Use [Link]() to select elements using CSS selectors.
// Selecting an element by ID
const elementById = [Link]('myElementId');
Modifying Elements:
Changing HTML Content:
You can change the content of an element using the innerHTML property.
Changing Element Attributes:
Use the setAttribute() method to modify element attributes.
Modifying Element Styles:
Alter the styles of elements by accessing their style property.
// Removing an element
[Link](newElement);
// Cloning an element
const cloneElement = [Link](true);
Event Handling:
Adding Event Listeners:
Attach event listeners to elements using addEventListener().
Event Object and Event Types:
Event listeners receive an event object with details about the event, including its type.
Event Bubbling and Event Delegation:
Understand how events propagate through the DOM and use event delegation for efficiency.
Do refer the table provided towards the end of the document for more such events available in
javascipt.
DOM Traversal:
Navigating the DOM Tree:
You can navigate up and down the DOM tree using properties like parentElement, childNodes, etc.
Parent, Child, and Sibling Elements:
Access parent, child, and sibling elements with parentNode, children, nextSibling, and previousSibling.
Finding Elements within a Parent:
Use querySelectorAll() on a parent element to find specific child elements.
Example:
[Link](eval(s1));
// returns the number 4
[Link](eval(s2));
// returns the string "2 + 2"
Strings are immutable:
It’s important to know that in JavaScript, strings are immutable. This means that once a
string is created, its contents cannot be changed.
Instead, you must create a new string representing the modified version when you want to
modify a string.
For example, if you have a string assigned to a variable, you cannot modify it. Instead, you
will create a new string and assign the new string to the same variable like this:
let name = "John Doe";
name = "Jane";
This means that the original string "John Doe" still exists in memory, but the
variable name now refers to the new string "Jane".
String methods :-
length - This method returns the number of characters in a string. For example, the
following code will return 11:
concat - This method is used to concatenate (combine) two or more strings. For example,
the following code will return "Hello World":
slice(start, end)
substring(start, end)
substr(start, length)
String slice()
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: start position, and end position (end not included).
Example
If you omit the second parameter, the method will slice out the rest of the string:
Example
let text = "Please visit Microsoft!";
let newText = [Link]("Microsoft", "Google");
Note
The replace() method does not change the string it is called on.
The replace() method returns a new string.
The replace() method replaces only the first match
If you want to replace all matches, use a regular expression with the /g flag set. See
examples below.
Example
[Link](",") // Split on commas
[Link](" ") // Split on spaces
[Link]("|") // Split on pipe
If the separator is omitted, the returned array will contain the whole string in index [0].
Example:-
let te = "How are you doing today?";
const myArray = [Link](" ");
[Link](myArray);
The charCodeAt() method returns the unicode of the character at a specified index in a
string:
The method returns a UTF-16 code (an integer between 0 and 65535).
Example
let text = "HELLO WORLD";
let char = [Link](0);
//0th position value’s code is displayed as output
Example
let text = "HELLO WORLD";
let char = text[0];
// 0th position value is getting stored in char.
Search Methods
indexOf - This method is used to find the index of a specific character or substring in
a string. For example, the following code will return 6:
String search()
The search() method searches a string for a string (or a regular expression) and
returns the position of the match:
Examples
//input:
let data="Hi Welcome!!! to kmit. kmit locates in HYD"
[Link]([Link]("kmit"))
//output: 17
Example-2:
//input:
let data="Hi Welcome!!! to kmit. kmit locates in HYD''
[Link]([Link]("kmit","KMIT"))
//output:
Hi Welcome!!! to KMIT. kmit locates in HYD
Example 3:
//input:
let data="Hi Welcome!!! to kmit. kmit locates in HYD"
[Link]([Link](" "))
[Link]([Link]("kmit"))
//output:
[ 'Hi', 'Welcome!!!', 'to', 'kmit.', 'kmit', 'locates', 'in', 'HYD' ]
[ 'kmit', index: 17, input: 'Hi Welcome!!! to kmit. kmit locates in HYD',
groups: undefined ]
Basic regexes
/abc/
For example:
Input:
const data1="Hi Welcome!!! to kmit. kmit locates in HYD"
const rex=/kmit/g
let result=[Link](rex)
[Link]([Link](result));
Output:
0: ['kmit', index: 17, input: 'Hi Welcome!!! to kmit. kmit locates in HYD']
1: ['kmit', index: 23, input: 'Hi Welcome!!! to kmit. kmit locates in HYD']
length: 2
Example-2:
function RegularExpression()
{
let data1="Hi Welcome!!! to kmit. kmit locates in HYD"
let regex = new RegExp(/.[aeiou]\w/g);
let res=[Link](regex);
[Link]([Link](res));
}
RegularExpression()
Regular Expression Flags:
Symbol Description
[Link] below example & Use look behind then print words containing (the) use ignore case?
Ans: /(?<=The)/gi These there that there thin them thesis turn.
[Link] Number starts with 8 or 9 & total digit should be 10
[Link] Character Uppercase contains lower case alphabets only 1 digit allowed in between
[Link] id
[Link] contains Min length 7 & max length is 15 contains at least special symbol, upper & lower
case?
[Link] & ends with vowel
2. Ans: /^T[a-z]+[aeiou]$/gm
4 Ans: /([A-Z])\w*/g
6 Ans: /[89][0-9]{9}/g
7 Ans: /[A-Z][a-z]*[0-9][a-z]*/g
8 Ans: /[a-zA-Z0-9_\-\.]+[@][a-z]+[\.][a-z]{2,3}/g
9 Ans: /[A-Za-z0-9@*&^%!#]{8,15}/g
10 Ans: /^[aeiou][a-z]+[aeiou]$/g
Arrays
An array in JavaScript is a data structure used to store multiple values in a
single variable. It can hold various data types and allows for dynamic resizing.
Elements are accessed by their index, starting from 0.
Syntax:
let arrayName = [value1, value2, ...];
// Creating an Empty Array
let names = [];
[Link](names);
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "Javascript", "React"];
[Link](courses);
2. Creating an Array using JavaScript new Keyword (Array Constructor)
The “Array Constructor” refers to a method of creating arrays by invoking the
Array constructor function. This approach allows for dynamic initialization and
can be used to create arrays with a specified length or elements.
Syntax:
let arrayName = new Array();
// Creating and Initializing an array with values
let courses = new Array("HTML", "CSS", "Javascript", "React");
[Link](courses);
1. Accessing Elements of an Array
Any element in the array can be accessed using the index number. The index in
the arrays starts with 0.
JavaScript
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "Javascript", "React"];
Output
HTML
CSS
Output
First Item: HTML
3. Accessing the Last Element of an Array
We can access the last array element using [[Link] – 1] index number.
JavaScript
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "JavaScript", "React"];
Output
First Item: React
4. Modifying the Array Elements
Elements in an array can be modified by assigning a new value to their
corresponding index.
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "Javascript", "React"];
[Link](courses);
courses[1]= "Bootstrap";
[Link](courses);
Output
[ 'HTML', 'CSS', 'Javascript', 'React' ]
[ 'HTML', 'Bootstrap', 'Javascript', 'React' ]
5. Adding Elements to the Array
Elements can be added to the array using methods like push() and unshift().
The push() method add the element to the end of the array.
The unshift() method add the element to the starting of the array.
JavaScript
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "Javascript", "React"];
[Link](courses);
Output
[ 'Web Development', 'HTML', 'CSS', 'Javascript', 'React', '[Link]' ]
6. Removing Elements from an Array
To remove the elements from an array we have different methods
like pop(), shift(), or splice().
The pop() method removes an element from the last index of the array.
The shift() method removes the element from the first index of the array.
The splice() method removes or replaces the element from the array.
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "Javascript", "React", "[Link]"];
[Link]("Original Array: " + courses);
Output
Array After Increase the Length: [ 'HTML', 'CSS', 'Javascript', 'React', '[Link]',
<2 empty items> ]
Array After Decrease the Length: [ 'HTML', 'CSS' ]
9. Iterating Through Array Elements
We can iterate array and access array elements using for loop and forEach loop.
Example: It is an example of for loop.
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "JavaScript", "React"];
Output
HTML
CSS
JavaScript
React
Example: It is the example of [Link]() loop.
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "JavaScript", "React"];
// Iterating through forEach loop
[Link](function myfunc(elements) {
[Link](elements);
});
Output
HTML
CSS
JavaScript
React
10. Array Concatenation
Combine two or more arrays using the concat() method. It returns new array
containing joined arrays elements.
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "JavaScript", "React"];
let otherCourses = ["[Link]", "[Link]"];
Output
Concatenated Array: [ 'HTML', 'CSS', 'JavaScript', 'React', '[Link]', '[Link]'
]
11. Conversion of an Array to String
We have a built-in method toString() to converts an array to a string.
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "JavaScript", "React"];
Output
HTML,CSS,JavaScript,React
12. Check the Type of an Arrays
The JavaScript typeof operator is used ot check the type of an array. It returns
“object” for arrays.
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "JavaScript", "React"];
[Link](delete [Link]);
[Link](emp);
Output
true
{ firstName: 'Raj', lastName: 'Kumar' }
JavaScript Array flat() Method
The flat() method is used to flatten the array i.e. it merges all the given array
and reduces all the nesting present in it.
Syntax:
[Link]([depth])
Example: Reducing the nesting of the given array using the flat() method.
// Creating multilevel array
const arr = [['1', '2'], ['3', '4', '5',['6'], '7']];
function hello() {
return [Link]([Link]);
}
[Link](sub);
Output
[ [ 2, 3, 4, 5 ], [ 2, 3, 4, 5 ], [ 2, 3, 4, 5 ], [ 2, 3, 4, 5 ] ]
Array reverse() method
The reverse() method is used to reverse the order of elements in an array. It
modifies the array in place and returns a reference to the same array with the
reversed order.
Syntax:
[Link]()
Example: Here is an example shows the use of the Array reverse() method.
let array = [1, 2, 3, 4, 5];
[Link]();
[Link](array);
Output
[ 5, 4, 3, 2, 1 ]
Array values() method
The values() method returns a new Array Iterator object that contains the values
for each index in the array.
Syntax:
[Link]()
Example: Here is an example shows the use of the Array values() method.
const fruits = ["Apple", "Banana", "Cherry"];
Output
Apple
Banana
Cherry
Functions in JavaScript
A function in JavaScript is a reusable block of code that performs a specific
task. You define it once, and then you can run (or “call”) it whenever you need
that task done in your program.
A JavaScript function runs when it is “called” by some part of your code.
Syntax: The basic syntax to create a function in JavaScript is shown below.
function functionName(Parameter1, Parameter2, ...)
{
// Function body
}
To create a function in JavaScript, we have to first use the keyword function,
separated by the name of the function and parameters within parenthesis. The
part of the function inside the curly braces {} is the body of the function.
In javascript, functions can be used in the same way as variables for
assignments, or calculations.
Why Functions?
Functions can be used multiple times, reducing redundancy.
Break down complex problems into manageable pieces.
Manage complexity by hiding implementation details.
Can call themselves to solve problems recursively.
Function Invocation
The function code you have written will be executed whenever it is called.
Triggered by an event (e.g., a button click by a user).
When explicitly called from JavaScript code.
Automatically executed, such as in self-invoking functions.
Function Definition
Before, using a user-defined function in JavaScript we have to create one. We
can use the above syntax to create a function in JavaScript.
A function definition is sometimes also termed a function declaration or
function statement. Below are the rules for creating a function in JavaScript:
Every function should begin with the keyword function followed by,
A user-defined function name that should be unique,
A list of parameters enclosed within parentheses and separated by
commas,
A list of statements composing the body of the function enclosed within
curly braces {}.
Example: This example shows a basic declaration of a function in javascript.
function calcAddition(number1, number2) {
return number1 + number2;
}
[Link](calcAddition(6,9));
Output
15
In the above example, we have created a function named calcAddition,
This function accepts two numbers as parameters and returns the addition
of these two numbers.
Accessing the function with just the function name without () will return
the function object instead of the function result.
There are three ways of writing a function in JavaScript:
Function Declaration: It declares a function with a function keyword. The
function declaration must have a function name.
Syntax:
function hello(paramA, paramB) {
// Set of statements
}
Function Expression
It is similar to a function declaration without the function name. Function
expressions can be stored in a variable assignment.
Syntax:
let hello= function(paramA, paramB) {
// Set of statements
}
Example: This example explains the usage of the Function expression.
const square = function (number) {
return number * number;
};
const x = square(4); // x gets the value 16
[Link](x);
Output
16
Functions as Variable Values
Functions can be used the same way as you use variables.
Example:
// Function to convert Fahrenheit to Celsius
function toCelsius(fahrenheit) {
return (fahrenheit - 32) * 5/9;
}
Arrow Function:
Arrow Function is one of the most used and efficient methods to create a
function in JavaScript because of its comparatively easy implementation. It is a
simplified as well as a more compact version of a regular or normal function
expression or syntax.
Syntax:
let function_name = (argument1, argument2 ,..) => expression
Example: This example describes the usage of the Arrow function.
const a = ["Hydrogen", "Helium", "Lithium", "Beryllium"];
const a2 = [Link](function (s) {
return [Link];
});
Output
Normal way [ 8, 6, 7, 9 ]
Using Arrow Function [ 8, 6, 7, 9 ]
Function Parameters
Parameters are additional information passed to a function. For example, in the
above example, the task of the function calcAddition is to calculate the addition
of two numbers. These two numbers on which we want to perform the addition
operation are passed to this function as parameters. The parameters are passed
to the function within parentheses after the function name and separated by
commas. A function in JavaScript can have any number of parameters and also
at the same time, a function in JavaScript can not have a single parameter.
Example: In this example, we pass the argument to the function.
function multiply(a, b) {
b = typeof b !== "undefined" ? b : 1;
return a * b;
}
[Link](multiply(69));
Output
69
Calling Functions
After defining a function, the next step is to call them to make use of the
function. We can call a function by using the function name separated by the
value of parameters enclosed between the parenthesis and a semicolon at the
end. The below syntax shows how to call functions in JavaScript:
Syntax:
functionName( Value1, Value2, ..);
Example: Below is a sample program that illustrates the working of functions
in JavaScript:
function welcomeMsg(name) {
return ("Hello " + name + " welcome to WT");
// creating a variable
let nameVal = "Admin";
Output
Hello Admin welcome to WT
Return Statement
There are some situations when we want to return some values from a function
after performing some operations. In such cases, we can make use of the return
statement in JavaScript. This is an optional statement and most of the time the
last statement in a JavaScript function. Look at our first example with the
function named as calcAddition. This function is calculating two numbers and
then returns the result.
Syntax: The most basic syntax for using the return statement is:
return value;
The return statement begins with the keyword return separated by the value
which we want to return from it. We can use an expression also instead of
directly returning the value.
types Of Functions in JavaScript
1. Named function:
A Named function is one that we write in code and then use whenever we need
it by referencing its name and providing it with some parameters. Named
functions come in handy when we need to call a function several times to give
various values to it or run it multiple times.
function add(a, b) {
return a + b;
}
[Link](add(5, 4));
Output
9
2. Anonymous function:
We can define a function in JavaScript without giving it a name. This nameless
function is referred to as the Anonymous function. A variable must be assigned
to an anonymous function.
let add = function (a, b) {
return a + b;
}
[Link](add(5, 4));
Output
9
3. Nested Functions:
A function in JavaScript can contain one or more inner functions. These Nested
Functions fall within the purview of the outer function. The inner function has
access to the variables and arguments of the outer function. However, variables
declared within inner functions cannot be accessed by outer functions.
function msg(firstName) {
function hey() {
[Link]("Hey " + firstName);
}
return hey();
}
msg("Ravi");
Output
Hey Ravi
4. Immediately invoked function expression:
The browser executes the invoked function expression as soon as it detects
it. Immediately invoked function expression has the advantage of running
instantly where it is situated in the code and producing direct output. That is, it
is unaffected by code that occurs later in the script and can be beneficial.
Output
Welcome to WT
JavaScript Rest parameter
The JavaScript Rest parameter allows a function to accept an indefinite number
of arguments as an array. It is represented by three dots (…) followed by the
parameter name and must be the last parameter in the function, enabling flexible
and dynamic argument handling.
Syntax
//... is the rest parameter (triple dots)
function functionname(...parameters)
{
statement;
}
Note: When … is at the end of the function parameter, it is the rest parameter. It
stores n number of parameters as an array. Let’s see how the rest parameter
works:
Example 1: Without Using the Rest Parameter
Javascript code demonstrating the passing arguments more than the parameters
without using rest parameter
function fun(a, b){
return a + b;
}
[Link](fun(1, 2)); // 3
[Link](fun(1, 2, 3, 4, 5)); // 3
Output
3
3
Explanation: In the above code example
Extra arguments beyond parameters are ignored without error.
Use … to collect additional arguments into an array.
Rest parameters allow flexible argument handling for functions.
Example 2: Using the Rest Parameter
JavaScript code demonstrating the addition of numbers using the rest
parameter.
// es6 rest parameter
function fun(...input) {
let sum = 0;
for (let i of input) {
sum += i;
}
return sum;
}
[Link](fun(1, 2)); //3
[Link](fun(1, 2, 3)); //6
[Link](fun(1, 2, 3, 4, 5)); //15
Output
3
6
15
Sets in JavaScript
Sets in JavaScript are collections of unique values, meaning no duplicates are
allowed. They provide efficient ways to store and manage distinct elements.
Sets support operations like adding, deleting, and checking the presence of
items, enhancing performance for tasks requiring uniqueness.
Syntax:
new Set([it]);
Parameter:
it: It is an iterable object whose all elements are added to the new set
created, If the parameter is not specified or null is passed then a new set
created is empty.
Return Value:
A new set object.
Example: This example shows the implementation of a JavaScript set.
// ["sumit","amit","anil","anish"]
let set1 = new Set(["sumit","sumit","amit","anil","anish"]);
// it is an empty set
let set4 = new Set();
Properties of Set in JavaScript:
[Link] – It returns the number of elements in the Set.
1. [Link]()
[Link]() adds the new element with a specified value at the end of the Set
object.
Syntax:
[Link](val);
Parameter:
val: It is a value to be added to the set.
Return value: The set object
Example: In this example, we are adding values into the set by using add()
method.
let set1 = new Set();
[Link](10);
[Link](20);
[Link](set1);
Output:
Set(5) {10, 20, 30, 40, 50}
2. [Link]()
[Link]() deletes an element with the specified value from the Set object.
Syntax:
[Link](val);
Parameter:
val: It is a value to be deleted from the set.
Return value: true if the value is successfully deleted from the set else returns
false.
Example: In this example, we are deleting the values into the set by using
delete() method.
let set1 = new Set("foooodiiiieee");
// deleting e from the set
// it prints true
[Link]([Link]('e'));
[Link](set1);
[Link](set2);
[Link]()
[Link](set2);
Output:
Set(5) {10, 20, 30, 40, 50}
Set(0) {size: 0}
4. [Link]()
[Link]() returns an iterator object which contains an array having the
entries of the set, in the insertion order.
Syntax:
[Link]();
Parameter:
This method does not take any parameter
Return value: It returns an iterator object that contains an array of [value,
value] for every element of the set, in the insertion order.
Example: In this example, we are using enteries() method.
let set1 = new Set();
[Link](50);
[Link](30);
[Link](40);
[Link](20);
[Link](10);
[Link]([Link]().value);
[Link]([Link]().value);
Output:
(2) [50, 50]
(2) [30, 30]
(2) [40, 40]
5. [Link]()
[Link]() returns true if the specified value is present in the Set object.
Syntax:
[Link](val);
Parameter:
val: The value to be searched in the Set
Return value: True if the value is present else it returns false.
Example: In this example, we are checking whether the value is present in the
set by using has() method.
let set1 = new Set();
[Link]([Link](50));
[Link]([Link](10));
Output:
true
false
6. [Link]()
[Link]() returns all the values from the Set in the same insertion order.
Syntax:
[Link]();
Parameter:
This method does not take any parameter
Return value: An iterator object that contains all the values of the set in the
same order as they are inserted.
7. [Link]()
[Link]() also returns all the values from the Set in the insertion order.
Note: It is similar to the values() in the case of Sets
Syntax:
[Link]();
Parameter:
This method does not take any parameter
Return Value: An iterator object that contains all the values of the set in the
same order as they are inserted.
Example: In this example, we are printing all the values of the set by using
keys() method.
let set1 = new Set();
[Link](getKeys);
Output:
SetIterator {50, 30, 40, 'WEb', 'WT'}
SetIterator {50, 30, 40, 'WEB', 'WT'}
8. [Link]()
[Link]() executes the given function once for every element in the Set, in
the insertion order.
Syntax:
[Link](callback[,thisargument]);
Parameter:
callback – It is a function that is to be executed for each element of the
Set.
o The callback function is provided with three parameters as
follows:
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
Output:
{value: 'sumit', done: false}
{value: 'amit', done: false}
{value: 'anish', done: false}
{value: undefined, done: true}
Set Operations in JavaScript
JavaScript subSet() Method:
It returns true if Set A is a subset of Set B. A Set A is said to be a subset of Set B,
if all the elements of Set A is also present in Set B. Now lets implement and use
the subset function.
Example: In this example, we are checking whether the given subset is present
in the given set or not and returning the result according to it.
[Link] = function(otherSet)
{
// if size of this set is greater
// than otherSet then it can't be
// a subset
if([Link] > [Link])
return false;
else
{
for(let elem of this)
{
// if any of the element of
// this is not present in the
// otherset then return false
if()
return false;
}
return true;
}
}
// prints true
[Link]([Link](setB));
// prints false
[Link]([Link](setC));
// prints true
[Link]([Link](setB));
Output:
true
false
true
JavaScript union() Method:
It returns a Set which consists of the union of Set A and Set B. A Set is said to be
a union of two sets, if it contains all elements of Set A as well as all elements
of Set B, but it doesn’t contain duplicate elements.
If an element is present in both Set A and Set B then the union of Set A and B
will contain a single copy of the element. Let’s implement and use the union
function
Example: In this example, we are merging the two sets.
[Link] = function(otherSet)
{
// creating new set to store union
let unionSet = new Set();
[Link]([Link]());
Output:
SetIterator {10, 20, 30, 40, 50, …}
JavaScript intersection() Method:
It returns the intersection of Set A and Set B. A Set is said to be the intersection
of Set A and B if contains an element which is present both in Set A and Set
B. Let’s implement and use the intersection function
Example: In this example, we are finding the insersection of two sets.
[Link] = function(otherSet)
{
// creating new set to store intersection
let intersectionSet = new Set();
[Link]([Link]());
Output:
SetIterator {40, 50}
JavaScript difference() Method:
It returns the Set which contains the difference between Set A and Set B. A Set is
said to be a difference between Set A and B if it contains set of elements e which
are present in Set A but not in Set B. Let’s implement and use the difference
function
Example: In this example, we are finding the difference of two sets.
[Link] = function(otherSet)
{
// creating new set to store difference
let differenceSet = new Set();
[Link](differenceSet);
Output:
Set(3) {10, 20, 30}
JavaScript Map
The JavaScript Map object holds key-value pairs and preserves the original
insertion order. It supports any value, including objects and primitives, as keys
or values. This feature allows for efficient data retrieval and manipulation,
making Map a versatile tool for managing collections.
On iterating a map object returns the key, and value pair in the same order as
inserted. Map() constructor is used to create Map in JavaScript.
JavaScript Map has a property that represents the size of the map.
Example:
Input:
let map1 = new Map([
[1 , 10], [2 , 20] ,
[3, 30],[4, 40]
]);
[Link]("Map1: ");
[Link](map1);
Output:
// Map1:
// Map(4) { 1 => 10, 2 => 20, 3 => 30, 4 => 40 }
Steps to Create a Map
Passing an Array to new Map()
Create a Map and use [Link]()
Examples of JavaScript Map
new Map()
In this we use new Map() constructor,
Example: In this example, a Map named prices is created to associate product
names with their respective prices, allowing for efficient retrieval and
management of price information.
// Creating a Map for product prices
const prices = new Map([
["Laptop", 1000],
["Smartphone", 800],
["Tablet", 400]
]);
[Link]()
You can add elements to a Map with the set() method.
Example: In this example, the [Link]() method is employed to add product
prices to the Map named prices.
// Creating a Map for product prices
const prices = new Map();
// Using [Link]() to add product prices
[Link]('Laptop', 1000);
[Link]('Smartphone', 800);
// The Map now contains { 'Laptop' => 1000, 'Smartphone' => 800 }
Example 1: In this example, we will create a basic map object
JavaScript
let map1 = new Map([
[1, 2],
[2, 3],
[4, 5]
]);
[Link]("Map1");
[Link](map1);
[Link]("Map2");
[Link](map2);
Output
Map1
Map(3) { 1 => 2, 2 => 3, 4 => 5 }
Map2
Map(3) {
'firstname' => 'sumit',
'lastname' => 'ghosh',
'website' => 'WT'
}
Example 2: This example adds elements to the map using set() method.
JavaScript
let map1 = new Map();
[Link]("FirstName", "Shobhit");
[Link]("LastName", "Sharma");
[Link]("website", "WT");
[Link](map1);
Output
Map(3) {
'FirstName' => 'Shobhit',
'LastName' => 'Sharma',
'website' => 'WT'
}
Methods of JavaScript Map
set(key, value): Adds or updates an element with a specified key and
value.
get(key): Returns the value associated with the specified key.
has(key): Returns a boolean indicating whether an element with the
specified key exists.
delete(key): Removes the element with the specified key.
clear(): Removes all elements from the Map.
size: Returns the number of key-value pairs in the Map.
This example explains the use of Map methods like has(), get(), delete(),
and clear().
JavaScript
let map1 = new Map();
[Link](map1);
[Link]("map1 has website ? "+
[Link]("website"));
[Link]();
[Link](map1);
Output
Map(5) {
'first name' => 'sumit',
'last name' => 'ghosh',
'website' => 'WT',
'friend 1' => 'gourav',
'friend 2' => 'sourav'
}
map1 has website ? true
map1 has friend 3 ? false
get...
Advantages of Map
Map object provided by ES6. A key of a Map may occur once, which will be
unique in the map’s collection. There are slight advantages to using a map rather
than an object.
Unique Keys: A key can occur only once, ensuring uniqueness within the
collection.
Security: No default keys are stored; only what is explicitly added,
making it safer.
Flexible Key Types: Any value (object, function, etc.) can be used as a
key.
Order: Maintains the order of entry insertion.
Size Property: The size property makes it easy to retrieve the number of
elements.
Performance: Operations on Maps can be performed efficiently.
Difference between Map and set
Map Set
[Link](person).forEach(key => {
[Link](key + ": " + person[key]);
});
Object Methods
1. [Link](obj) – Returns an array of keys (property names).
2. [Link](obj) – Returns an array of values.
3. [Link](obj) – Returns an array of [key, value] pairs.
[Link](ageValue); // Output: 28
In this example, key is dynamically used to reference the age property, and its
value is assigned to the ageValue variable.
Combining Object Destructuring with Array Destructuring
You can combine object and array destructuring for complex structures.
let people = [
{ name: "Hank", age: 50 },
{ name: "Ivy", age: 40 }
];
[Link]([Link]); // John
[Link]([Link][1]); // Python
5. JSON Arrays
JSON can also be an array:
const jsonArray = [
{ "name": "Alice", "age": 25 },
{ "name": "Bob", "age": 28 },
{ "name": "Charlie", "age": 22 }
];
[Link](jsonArray[1].name); // Bob
Synchronous Code
When we write a program in JavaScript, it executes line by line. When a line is completely
executed, then and then only does the code move forward to execute the next line. This is
called synchronous code. .
Synchronous is a blocking architecture, so the execution of each operation is dependent on
the completion of the one before it. Each task requires an answer before moving on to the
next iteration. Synchronous code is written from top to bottom
Sync is slower and more methodical
Sync is single-thread, so only one operation or program will run at a time.
Sync is blocking — it will only send the server one request at a time and will wait for that
request to be answered by the server.
[Link]("synchronous.");
[Link]("synchronous javascript!");
[Link]("Be good do good");
Asynchronous
With asynchronous code, multiple tasks can execute at the same time while tasks in the
background finish. This is what we call non-blocking code. The execution of other code
won't stop while an asynchronous task finishes its work.
Async is multi-thread, which means operations or programs can run in parallel. Async
increases throughput because multiple operations can run at the same time. Async is non-
blocking, which means it will send multiple requests to a server.
JavaScript is single-threaded. This means that it carries out asynchronous operations via the
callback queue and event loop. Asynchronous is a non-blocking architecture, so the
execution of one task isn’t dependent on other. Tasks can run simultaneously.
A JavaScript function call called the setTimeout() function, which allows us to run javascript
code after a certain amount of time.
After the specified time, the setTimeout() method executes a block of code. The method only
runs the code once.
[Link]("async");
setTimeout(function(){
[Link]("Asynchronous");
}, 10000)
[Link]("asynchronous again!");
Techniques for writing asynchronous:
• Callbacks
• Promises
• Async/await
"A callback function is a function passed into another function as an argument, which is
then invoked inside the outer function to complete some kind of routine or action."
Callbacks are used in arrays, timer functions, promises, event handlers, and much more.
function add(x,y){
return x+y
}
function divide(x,y){
return x/y
}
The shape of callback hell is like a pyramid and is also called the “pyramid of doom”. It makes
the code very difficult to maintain and understand. Here's an example of callback hell:
setTimeout(() =>{
[Link]("One Second"); When one second has passed, the code logs
setTimeout(() =>{ "one seconds". Then there's another call which
runs after one more second and logs "two
[Link]("Two Seconds"); seconds" and it goes on and on.
setTimeout(() =>{
[Link]("Three Seconds"); We can escape this callback hell using
setTimeout(() =>{ something call Promises in asynchronous
[Link]("Four Seconds"); JavaScript.
setTimeout(() =>{
[Link]("Five Seconds");
}, 1000)
}, 1000)
}, 1000)
}, 1000)
}, 1000)
There are ways to handle callbacks.
1. Use of promise: a promise can be generated for each callback. When the callback is
successful, the promise is resolved, and if the callback fails, the promise is rejected.
2. Use of async-await: asynchronous functions are executed sequentially with the use of
await; execution stops until the promise is revolved and function execution is successful.
Promise
An async promise operation’s eventual success or failure is represented as a JavaScript
object. It enables the creation of asynchronous code that works and appears synchronous.
A promise, in our context, is something that will take some time to do. A promise has
three possible states: pending, fulfilled, or rejected.
Pending: the promise has been created, and the asynchronous function it's associated with
has not succeeded or failed yet. This is the state your promise is in when it's returned from a
call to fetch(), and the request is still being made.
Fulfilled: the asynchronous function has succeeded. When a promise is fulfilled, its then()
handler is called.
Rejected: the asynchronous function has failed. When a promise is rejected, its catch()
handler is called.
When using promises, we don't need to relay on callbacks which helps us avoid callback
hell.
"Producing code" is code that can take some time
A Promise is a JavaScript object that links producing code and consuming code
Create a Promise
To create a promise object, we use the Promise() constructor.
If the promise returns successfully, the resolve() function is called. And, if an error occurs, the reject() function is
called.
The constructor function takes a function as an argument. This function is called the executor function.
[Link](countValue);
How to handle a Promise once you've created it
A Promise uses an executor function to complete a task (mostly asynchronously). A
consumer function (that uses an outcome of the promise) should get notified when the
executor function is done with either resolving (success) or rejecting (error).
The handler methods, .then(), .catch() and .finally(), help to create the link between the
executor and the consumer functions so that they can be in sync when a promise
resolves or rejects.
The .then() method should be called on the promise object to handle a result (resolve) or an
error (reject).
Usually, the .then() method should be called from the consumer function where you would
like to know the outcome of a promise's execution.
It takes data from the resolved promise. It can take up to two arguments which are
callback functions for the fulfilled and rejected cases respectively.
Syntax:
then(successFunc, rejectFunc)
successFunc: This asynchronous callback function gets executed when the Promise is
resolved
rejectFunc: This asynchronous callback function gets executed when Promise is rejected
JavaScript Promise .catch() method is called whenever a promise is rejected. This method
itself returns a promise so it can also be used to chain promises. This method is used for error
handling. This method is mainly used after .then to chain a promise and handle reject condition.
Syntax:
.catch(()=>{})
Parameter: This method takes a callback function that decides what action to perform when the
promise is rejected
Return Type: This method returns a promise which is in the pending state even if the previous
promise is finished.
Example:-
let x = 100;
let y = 10;
let prom1 = new Promise((resolve, reject) => {
if (x == y) {
resolve("Equal Values")
} else {
reject("Unequal Values")
}
})
// async function
async function asyncFunc() {
[Link](result);
[Link]('hello');
}
[Link](result);
}
catch(error) {
[Link](error);
}
}
asyncFunc();
Error handling in asynchronous JavaScript
Error handling in asynchronous JavaScript involves try/catch blocks, which are used in JavaScript to
catch any mistakes that might happen throughout the asynchronous process.
try{
alert("This is an error function!")
}catch(e){
alert(e)
}
A catch block can have parameters that will give you error information. Generally, the catch block is
used to log an error or display specific messages to the user. Now that the “incrementDigits()“
asynchronous function has an error handler function.
Example:-
let num = prompt("insert a number greater than 30 but less than 40");
try {
if (isNaN(num)) throw "Not a number (☉。☉)!";
else if (num > 40)
throw "Did you even read the instructions ಠ︵ಠ, less than 40";
else if (num <= 30) throw "Greater than 30 (;")ب_ب
}catch (e) {
alert(e);
}
Example:-
let num = prompt("insert a number greater than 30 but less than 40");
try {
if (isNaN(num)) throw "Not a number!";
else if (num > 40)
throw "Did you even read the instructions, less than 40";
else if (num <= 30) throw "Greater than 30”
}catch (e) {
alert(e);
}