0% found this document useful (0 votes)
14 views107 pages

Mastering DOM Manipulation Techniques

The document provides an overview of the Document Object Model (DOM) and its significance in web development, detailing methods for accessing, modifying, creating, and removing elements within the DOM. It also covers event handling and DOM traversal techniques, alongside a comprehensive list of JavaScript string methods and regular expressions. Key concepts include string immutability, various string manipulation methods, and the creation and use of regular expressions in JavaScript.

Uploaded by

Raj Gopal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views107 pages

Mastering DOM Manipulation Techniques

The document provides an overview of the Document Object Model (DOM) and its significance in web development, detailing methods for accessing, modifying, creating, and removing elements within the DOM. It also covers event handling and DOM traversal techniques, alongside a comprehensive list of JavaScript string methods and regular expressions. Key concepts include string immutability, various string manipulation methods, and the creation and use of regular expressions in JavaScript.

Uploaded by

Raj Gopal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DOM Manipulations

DOM and its importance:


The Document Object Model (DOM) is a programming interface for web documents. It represents the
structure of a web page and allows you to interact with and manipulate its elements using JavaScript.
DOM manipulation is crucial for creating dynamic web applications. It allows to update the content,
structure, and style of a web page in response to user actions, making your website interactive and
responsive.
DOM Tree Structure:
The DOM is structured as a tree, with the Document Object at the top. Each HTML element becomes
a node in this tree, and you can traverse, access, and modify these nodes.

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');

// Selecting elements by class


const elementsByClass = [Link]('myClass');

// Selecting elements by tag name


const elementsByTag = [Link]('div');

// Selecting elements using CSS selectors


const elementsBySelector = [Link]('.myClass p');

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.

// Changing HTML content


[Link] = 'New Content';

// Changing element attributes


[Link]('src', '[Link]');

// Modifying element styles


[Link] = 'blue';

Creating and Removing Elements:


Creating New Elements:
You can create new elements using [Link]().
Appending and Removing Elements:
Add or remove elements from the DOM using appendChild() and removeChild().
Cloning Elements:
Use cloneNode() to create copies of elements.

// Creating a new element


const newElement = [Link]('div');

// Appending the new element


[Link](newElement);

// 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.

// Adding an event listener


[Link]('click', (event) => {
alert('Element clicked!');
});

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.

// Accessing parent element


const parentElement = [Link];

// Accessing child elements


const childElements = [Link];

// Finding elements within a parent


const childDivs = [Link]('div');
Here is a list of available events:

Event Occurs When


abort The loading of a media is aborted
afterprint A page has started printing
animationend A CSS animation has completed
animationiteration A CSS animation is repeated
animationstart A CSS animation has started
beforeprint A page is about to be printed
beforeunload Before a document is about to be unloaded
blur An element loses focus
canplay The browser can start playing a media (has buffered enough to begin)
canplaythrough The browser can play through a media without stopping for buffering
change The content of a form element has changed
click An element is clicked on
contextmenu An element is right-clicked to open a context menu
copy The content of an element is copied
cut The content of an element is cut
dblclick An element is double-clicked
drag An element is being dragged
dragend Dragging of an element has ended
dragenter A dragged element enters the drop target
dragleave A dragged element leaves the drop target
dragover A dragged element is over the drop target
dragstart Dragging of an element has started
drop A dragged element is dropped on the target
durationchange The duration of a media is changed
ended A media has reach the end ("thanks for listening")
error An error has occurred while loading a file
focus An element gets focus
focusin An element is about to get focus
focusout An element is about to lose focus
fullscreenchange An element is displayed in fullscreen mode
fullscreenerror An element can not be displayed in fullscreen mode
hashchange There has been changes to the anchor part of a URL
input An element gets user input
invalid An element is invalid
keydown A key is down
keypress A key is pressed
keyup A key is released
load An object has loaded
loadeddata Media data is loaded
loadedmetadata Meta data (like dimensions and duration) are loaded
loadstart The browser starts looking for the specified media
message A message is received through the event source
mousedown The mouse button is pressed over an element
mouseenter The pointer is moved onto an element
mouseleave The pointer is moved out of an element
mousemove The pointer is moved over an element
mouseover The pointer is moved onto an element
mouseout The pointer is moved out of an element
mouseup A user releases a mouse button over an element
mousewheel Deprecated. Use the wheel event instead
offline The browser starts working offline
online The browser starts working online
open A connection with the event source is opened
pagehide User navigates away from a webpage
pageshow User navigates to a webpage
paste Some content is pasted in an element
pause A media is paused
play The media has started or is no longer paused
playing The media is playing after being paused or buffered
popstate The window's history changes
progress The browser is downloading media data
ratechange The playing speed of a media is changed
resize The document view is resized
reset A form is reset
scroll An scrollbar is being scrolled
search Something is written in a search field
seeked Skipping to a media position is finished
seeking Skipping to a media position is started
select User selects some text
show A <menu> element is shown as a context menu
stalled The browser is trying to get unavailable media data
storage A Web Storage area is updated
submit A form is submitted
suspend The browser is intentionally not getting media data
timeupdate The playing position has changed (the user moves to a different point in the media)
toggle The user opens or closes the <details> element
touchcancel The touch is interrupted
touchend A finger is removed from a touch screen
touchmove A finger is dragged across the screen
touchstart A finger is placed on a touch screen
transitionend A CSS transition has completed
unload A page has unloaded
volumechange The volume of a media is changed (includes muting)
waiting A media is paused but is expected to resume (e.g. buffering)
wheel The mouse wheel rolls up or down over an element
JavaScript Strings
JavaScript Strings are useful for holding data that can be represented in text form.
A JavaScript string is zero or more characters written inside quotes.

Example:

let text= “Keshav Memorial Institute of Technology.”

Text => variable name


Keshav Memorial Institute of Technology => String literal encoded with double
quotes

You can use single or double quotes:

let carName1 = "BMW"; // Double quotes


let carName2 = 'BMW'; // Single quotes
const s1 = "2 + 2";
// creates a string primitive

const s2 = new String("2 + 2");


// creates a String object

[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:

var str = "Hello World";


[Link]([Link]);

concat - This method is used to concatenate (combine) two or more strings. For example,
the following code will return "Hello World":

var str1 = "Hello";


var str2 = " World";
[Link]([Link](str2));
Extracting String Parts

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

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

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


let text = "Apple, Banana, Kiwi";
let part = [Link](7, 13);

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

let text = "Apple, Banana, Kiwi";


let part = [Link](7);
String substring()

substring() is similar to slice().


The difference is that start and end values less than 0 are treated as 0 in substring().
Example:
let str = "Apple, Banana, Kiwi";
let part = [Link](7, 13);
If you omit the second parameter, substring() will slice out the rest of the string.

Replacing String Content


The replace() method replaces a specified value with another value in a 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.

toUpperCase and toLowerCase - These methods are used to convert a string to


uppercase or lowercase letters. For example, the following code will return "HELLO
WORLD" and "hello world" respectively:

var str = "Hello World";


[Link]([Link]());
[Link]([Link]());
String split()
A string can be converted to an array with the split() method:

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);

o/p:- [ 'How', 'are', 'you', 'doing', 'today?' ]


String charCodeAt()

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:

var str = "Hello World";


[Link]([Link]("W"));

String search()
The search() method searches a string for a string (or a regular expression) and
returns the position of the match:

Examples

let text = "Please locate where 'locate' occurs!";


[Link]([Link]("locate"));
let text = "Please locate where 'locate' occurs!";
[Link]([Link](/locate/));
JavaScript String match()
The match() method returns an array containing the results of matching a string against a string (or a
regular expression).
Examples
Perform a search for "ain":
let text = "The rain in SPAIN stays mainly in the plain";
[Link]("ain"); // array size =1

Perform a search for "ain":


let text = "The rain in SPAIN stays mainly in the plain";
[Link](/ain/); // array size =1

Perform a global search for "ain":


let text = "The rain in SPAIN stays mainly in the plain";
[Link](/ain/g); //array size =3

Perform a global, case-insensitive search for "ain":


let text = "The rain in SPAIN stays mainly in the plain";
[Link](/ain/gi); // array size =4
Regular Expression:
Regular expressions are patterns used to match character combinations in strings. In
JavaScript, regular expressions are also objects. These patterns are used with the exec()
and test() methods of RegExp, and with the match(), matchAll(), replace(), replaceAll(),
search(), and split() methods of String. These string methods allow you to pass RegEx as
its parameter

Using String Methods


In JavaScript, regular expressions are often used with the two string methods: search()
and replace().
[Link] search() method uses an expression to search for a match, and returns the position
of the match.
[Link] replace() method returns a modified string where the pattern is replaced.
Example-1:

//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/

• a regular expression literal in JS is written /pattern/


• the simplest regexes simply match a given substring

• the above regex matches any line containing "abc"


▪ YES : "abc", "abcdef", "defabc", ".=.abc.=."
▪ NO : "fedcba", "ab c", "AbC", "Bash", ...
Create a RegEx :
There are two ways you can create a regular expression in JavaScript.

Using a regular expression literal:


The regular expression consists of a pattern enclosed between slashes /.

For example: cost regularExp = /abc/;

Here, /abc/ is a regular expression.

Using the RegExp() constructor function:


You can also create a regular expression by calling the RegExp() constructor
function.

For example:

const reguarExp = new RegExp('abc');


Example-1:

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

g g is used for global search which means


the search will not return after the first
match.
i i is used for case-insensitive search
meaning that a match can occur regardless
of the casing.
m m is used for multiline search.
u u is used for Unicode search
Quantifiers define quantities:
Expression Description

[abc] Should match any single of character


[^abc] Should not match any single character
[0-9] should match any decimal digit from 0 through 9
[a-z] should match any character from lowercase a through lowercase z.
[A-Z] should match any character from uppercase A through uppercase Z.
[a-Z] should match any character from lowercase a through uppercase Z.
[a-zA-Z0-9] Characters range lowercase a-z, uppercase A-Z and numbers.
[a-z-._] Match against character range lowercase a-z and ._ refers special character
(.*?) Capture everything enclosed with brackets
(com|info) Input should be "com" or "info"
{2} Exactly two characters
{2,3} Minimum 2 characters and Maximum 3 characters
{2,} More than 2 characters
Assignment Questions:

[Link] 5 letter word & last letter should be vowel? Ans:/\w{4}[aeiou]$/g

[Link] words that begins with T and ends with vowels?

The True Test Truth truth

[Link] the length of words whose size should be 4? Ans: /\w{4}/g

[Link] all words which contains First letter is Capital?

[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.

 Array: A data structure in JavaScript that allows you to store multiple


values in a single variable.
 Array Element: Each value within an array is called an element.
Elements are accessed by their index.
 Array Index: A numeric representation that indicates the position of an
element in the array. JavaScript arrays are zero-indexed, meaning the first
element is at index 0.
 Array Length: The number of elements in an array. It can be retrieved
using the length property.
1. Creating an Array using Array Literal
Creating an array using array literal involves using square brackets [] to define
and initialize the array. This method is concise and widely preferred for its
simplicity.

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"];

// Accessing Array Elements


[Link](courses[0]);
[Link](courses[1]);

Output
HTML
CSS

2. Accessing the First Element of an Array


The array indexing starts from 0, so we can access first element of array using
the index number.
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "JavaScript", "React"];

// Accessing First Array Elements


let firstItem = courses[0];

[Link]("First Item: ", firstItem);

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"];

// Accessing Last Array Elements


let lastItem = courses[[Link] - 1];
[Link]("First Item: ", lastItem);

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"];

// Add Element to the end of Array


[Link]("[Link]");
// Add Element to the beginning
[Link]("Web Development");

[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);

// Removes and returns the last element


let lastElement = [Link]();
[Link]("After Removing the last elements: " + courses);

// Removes and returns the first element


let firstElement = [Link]();
[Link]("After Removing the First elements: " + courses);

// Removes 2 elements starting from index 1


[Link](1, 2);
[Link]("After Removing 2 elements starting from index 1: " + courses);
Output
Original Array: HTML,CSS,Javascript,React,[Link]
After Removing the last elements: HTML,CSS,Javascript,React
After Removing the First elements: CSS,Javascript,React
After Removing 2 elements starting from index 1: CSS
7. Array Length
We can get the length of the array using the array length property.
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "Javascript", "React", "[Link]"];

let len = [Link];

[Link]("Array Length: " + len);


Output
Array Length: 5
8. Increase and Decrease the Array Length
We can increase and decrease the array length using the JavaScript length
property.
// Creating an Array and Initializing with Values
let courses = ["HTML", "CSS", "Javascript", "React", "[Link]"];

// Increase the array length to 7


[Link] = 7;
[Link]("Array After Increase the Length: ", courses);
// Decrease the array length to 2
[Link] = 2;
[Link]("Array After Decrease the Length: ", 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"];

// Iterating through for loop


for (let i = 0; i < [Link]; i++) {
[Link](courses[i])
}

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]"];

// Concatenate both arrays


let concateArray = [Link](otherCourses);
[Link]("Concatenated Array: ", concateArray);

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"];

// Convert array ot String


[Link]([Link]());

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"];

// Check type of array


[Link](typeof courses);

JavaScript Array delete Operator


The delete operator is used to delete the given value which can be an object,
array, or anything.
Syntax:
delete object
// or
delete [Link]
// or
delete object['property']
Example: Deleting the given object’s property by using the delete operator.
let emp = {
firstName: "Raj",
lastName: "Kumar",
salary: 40000
}

[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']];

// Flat the multilevel array


const flatArr= [Link](Infinity);
[Link](flatArr);
JavaScript [Link]() Method
The slice() method returns a new array containing a portion of the original array,
based on the start and end index provided as arguments
Syntax:
[Link] (startIndex , endIndex);
Example: Cover all slice() method corner cases.
// Original Array
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Case 1: Extract the first 3 elements of the array


const case1 = [Link](0, 3);
[Link]("First 3 Array Elements: ", case1);

// Case 2: Extract the last 3 array elements


const case2 = [Link](-3);
[Link]("Last 3 Array Elements: ", case2);

// Case 3: Extract elements from middle of array


const case3 = [Link](3, 7);
[Link]("Case 3: Extract elements from middle: ", case3);

// Case 4: Start index is greater than end index


const case4 = [Link](5, 2);
[Link]("Case 4: Start index is greater than end index: ", case4);

// Case 5: Negative start index


const case5 = [Link](-4, 9);
[Link]("Case 5: Negative start index: ", case5);
// Case 6: Negative end index
const case6 = [Link](3, -2);
[Link]("Case 6: Negative end index: ", case6);

// Case 7: Only start index is provided


const case7 = [Link](5);
[Link]("Case 7: Only start index is provided: ", case7);

// Case 8: Start index and end index are out of range


const case8 = [Link](15, 20);
[Link]("Case 8: Start and end index out of range: ", case8);

// Case 9: Start and end index are negative


// and out of range
const case9 = [Link](-15, -10);
[Link]("Case 9: Start and end index are negative"
+ " and out of range: ", case9);
Array some() Method
The some() method checks whether at least one of the elements of the array
satisfies the condition checked by the argument function.
Syntax:
[Link](callback(element, index, array), thisArg);
Example: Basic example of Array some() method.
function isGreaterThan5(element, index, array) {
return element > 5;
}
// Original array
let array = [2, 5, 8, 1, 4];
// Checking for condition in array
let value = [Link](isGreaterThan5);
[Link](value);
JavaScript Array map() Method
The map() method creates an array by calling a specific function on each
element present in the parent array. It is a non-mutating method. This method
iterates over an array and calls the function on every element of an array.
Syntax:
[Link](callback(currentValue, index, array), thisArg);
Example: Here is an example of the basic use of the Array map() method.
// Original array
let arr = [4, 9, 16, 25];

// Performing map method


let sub = [Link](hello);

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"];

// Get the iterator object


const iterator = [Link]();

// Iterate over the values using the iterator


for (const value of iterator) {
[Link](value);
}

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;
}

// Using the function to convert temperature


let temperatureInFahrenheit = 77;
let temperatureInCelsius = toCelsius(temperatureInFahrenheit);
let text = "The temperature is " + temperatureInCelsius + " Celsius";

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];
});

[Link]("Normal way ", a2); // [8, 6, 7, 9]

const a3 = [Link]((s) => [Link]);

[Link]("Using Arrow Function ", a3); // [8, 6, 7, 9]

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";

// calling the function


[Link](welcomeMsg(nameVal));

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.

let msg = (function() {


return "Welcome WT" ;
})();
[Link](msg);

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 contains 'f', 'o', 'd'


let set2 = new Set("fooooooood");

// it contains [10, 20, 30, 40]


let set3 = new Set([10, 20, 30, 30, 40, 40]);

// it is an empty set
let set4 = new Set();
Properties of Set in JavaScript:
[Link] – It returns the number of elements in the Set.

Methods of Set in JavaScript:

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);

// As this method returns


// the set object hence chaining
// of add method can be done.
[Link](30).add(40).add(50);

[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);

// deleting an element which is


// not in the set
// prints false
[Link]([Link]('g'));
Output:
true
Set(4) {'f', 'o', 'd', 'i'}
false
3. [Link]()
[Link]() removes all the element from the set.
Syntax:
[Link]();
Parameter:
This method does not take any parameter
Return value: Undefined
Example: In this example, we are clearing the values into the set by using
clear() method.
let set2 = new Set([10, 20, 30, 40, 50]);

[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);

// using entries to get iterator


let getEntriesArry = [Link]();

// each iterator is array of [value, value]


[Link]([Link]().value);

[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();

// adding element to the set


[Link](50);
[Link](30);

[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();

// adding element to the set


[Link](50);
[Link](30);
[Link](40);
[Link]("Web");
[Link]("WT");

// getting all the values


let getValues = [Link]();
[Link](getValues);

let getKeys = [Link]();

[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:

o the element key


o the element value
o the Set object to be traversed
 thisargument – Value to be used as this when executing the callback.
Return value: Undefined
9. [Link][@@iterator]()
[Link][@@iterator]() returns a Set iterator function which
is values() function by default.
Syntax:
set1[[Link]]();
Parameter:
This method does not take any parameter
Return value: A Set iterator function and it is values() by default.
Example: In this example, we are iterating the values from the set.
let set1 = new Set(["sumit","sumit","amit","anish"]);

let getit = set1[[Link]]();

[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(![Link](elem))
return false;
}
return true;
}
}

// using the subSet function

// Declaring different sets


let setA = new Set([10, 20, 30]);
let setB = new Set([50, 60, 10, 20, 30, 40]);
let setC = new Set([10, 30, 40, 50]);

// 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();

// iterate over the values and add


// it to unionSet
for (let elem of this)
{
[Link](elem);
}

// iterate over the values and add it to


// the unionSet
for(let elem of otherSet)
[Link](elem);

// return the values of unionSet


return unionSet;
}

// using the union function


// Declaring values for set1 and set2
let set1 = new Set([10, 20, 30, 40, 50]);
let set2 = new Set([40, 50, 60, 70, 80]);

// performing union operation


// and storing the resultant set in
// unionSet
let unionSet = [Link](set2);

[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();

// Iterate over the values


for(let elem of otherSet)
{
// if the other set contains a
// similar value as of value[i]
// then add it to intersectionSet
if([Link](elem))
[Link](elem);
}

// return values of intersectionSet


return intersectionSet;
}
// using intersection function
// Declaring values for set1 and set2
let set1 = new Set([10, 20, 30, 40, 50]);
let set2 = new Set([40, 50, 60, 70, 80]);

// performing union operation


// and storing the resultant set in
// intersectionset
let intersectionSet = [Link](set2);

[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();

// iterate over the values


for(let elem of this)
{
// if the value[i] is not present
// in otherSet add to the differenceSet
if(![Link](elem))
[Link](elem);
}

// returns values of differenceSet


return differenceSet;
}

// using difference function


// Declaring values for set1 and set2
let set1 = new Set([10, 20, 30, 40, 50]);
let set2 = new Set([40, 50, 60, 70, 80]);
// performing union operation
// and storing the resultant set in
// intersectionset
let differenceSet = [Link](set2);

[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);

let map2 = new Map([


["firstname", "sumit"],
["lastname", "ghosh"],
["website", "geeksforgeeks"]
]);

[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]("first name", "sumit");


[Link]("last name", "ghosh");
[Link]("website", "WT")
.set("friend 1","gourav")
.set("friend 2","sourav");

[Link](map1);
[Link]("map1 has website ? "+
[Link]("website"));

[Link]("map1 has friend 3 ? " +


[Link]("friend 3"));

[Link]("get value for key website "+


[Link]("website"));

[Link]("get value for key friend 3 "+


[Link]("friend 3"));
[Link]("delete element with key website "
+ [Link]("website"));

[Link]("map1 has website ? "+


[Link]("website"));

[Link]("delete element with key website " +


[Link]("friend 3"));

[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

It is a collection of key-value It is a collection of unique elements

Map is two-dimensional The set is one dimensional

In-built methods are used to access


Values are accessed using keys
values
Objects
In JavaScript, an object is a collection of key-value pairs, where each key is a
string (or symbol) and the corresponding value can be of any type, including
other objects or functions. Objects are one of the most important features in
JavaScript, often used to store and manipulate data.
Creating an Object
There are multiple ways to create objects in JavaScript:
1. Object Literals
This is the most common way of creating objects.
let person = {
name: "John",
age: 30,
isEmployed: true,
greet: function() {
[Link]("Hello, my name is " + [Link]);
}
};
In this example:
 name, age, and isEmployed are properties.
 greet is a method (function within an object).
2. Using the new Object() Syntax
let car = new Object();
[Link] = "Toyota";
[Link] = "Corolla";
[Link] = 2020;
3. Constructor Functions
You can define a template for creating objects using a constructor function.
function Person(name, age) {
[Link] = name;
[Link] = age;
[Link] = function() {
[Link]("Hi, I'm " + [Link]);
};
}

let person1 = new Person("Alice", 25);


let person2 = new Person("Bob", 22);

[Link](); // Output: Hi, I'm Alice


[Link](); // Output: Hi, I'm Bob
Accessing Object Properties
You can access properties in two ways:
1. Dot Notation
[Link]([Link]); // Output: John
2. Bracket Notation
[Link](person["name"]); // Output: John
Bracket notation is useful when the property name is dynamic or contains
special characters.
Adding or Modifying Properties
You can add or modify properties using both dot or bracket notation:
[Link] = 180; // Adding a new property
[Link] = 35; // Modifying an existing property
Deleting Properties
You can delete a property using the delete operator:
delete [Link];
Checking for Properties
You can check if an object has a property using either the in operator or the
hasOwnProperty() method.
[Link]("name" in person); // true
[Link]([Link]("age")); // true
Iterating Over Object Properties
You can iterate over object properties using a for...in loop or
[Link]()/[Link]()/[Link]().
for (let key in person) {
[Link](key + ": " + person[key]);
}

[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]([Link](person)); // ['name', 'age', 'isEmployed', 'greet']


[Link]([Link](person)); // ['John', 30, true, function() {...}]
[Link]([Link](person)); // [['name', 'John'], ['age', 30], ...]

Basic Array Destructuring Syntax


You can extract values from an array like this:
let [a, b] = [1, 2];
[Link](a); // Output: 1
[Link](b); // Output: 2
In the example above, the value 1 is assigned to a and the value 2 is assigned to
b.
1. Skipping Values
You can skip certain elements in the array by leaving empty spaces in the
destructuring pattern.
let [first, , third] = [10, 20, 30];
[Link](first); // Output: 10
[Link](third); // Output: 30
Here, the second element (20) is skipped because of the empty space between
the commas.
2. Default Values
If the array doesn't contain as many elements as you're destructuring, you can
assign default values.
let [x = 1, y = 2, z = 3] = [5];
[Link](x); // Output: 5
[Link](y); // Output: 2 (default value)
[Link](z); // Output: 3 (default value)
In this example, x takes the value 5, while y and z use their default values (2
and 3, respectively).
3. Rest Operator
The rest operator (...) can be used to capture the remaining elements in the array
into a new array.
let [first, ...rest] = [1, 2, 3, 4, 5];
[Link](first); // Output: 1
[Link](rest); // Output: [2, 3, 4, 5]
The first variable gets the value 1, and the rest variable collects the remaining
values into a new array: [2, 3, 4, 5].
4. Swapping Variables
Array destructuring makes it easy to swap variable values without needing a
temporary variable.
let a = 1;
let b = 2;
[a, b] = [b, a];
[Link](a); // Output: 2
[Link](b); // Output: 1
In this case, a and b swap their values in one line of code.
5. Destructuring with Functions
You can destructure arrays returned by functions.
function getCoordinates() {
return [10, 20];
}

let [x, y] = getCoordinates();


[Link](x); // Output: 10
[Link](y); // Output: 20
The values returned by getCoordinates() are destructured into x and y.
6. Nested Destructuring
If you have an array within an array, you can use nested destructuring to
extract values from both levels.
let [a, [b, c]] = [1, [2, 3]];
[Link](a); // Output: 1
[Link](b); // Output: 2
[Link](c); // Output: 3
In this example, the first value 1 is assigned to a, and the inner array [2, 3] is
further destructured into b and c.
Destructuring with Default Parameters in Functions
When functions accept arrays as arguments, you can destructure them directly
in the function parameter list, with or without default values.
function printDetails([name, age = 30]) {
[Link](`Name: ${name}, Age: ${age}`);
}

printDetails(["Alice", 25]); // Output: Name: Alice, Age: 25


printDetails(["Bob"]); // Output: Name: Bob, Age: 30 (default age)
In JavaScript, object destructuring allows you to extract properties from
objects and assign them to variables in a concise and readable way. It is
particularly useful when dealing with objects that have many properties,
allowing you to work with individual values without repeatedly referencing the
object.
Basic Object Destructuring Syntax
The basic syntax involves matching variable names with the property names in
the object:
let person = {
name: "John",
age: 30,
city: "New York"
};

let { name, age, city } = person;

[Link](name); // Output: John


[Link](age); // Output: 30
[Link](city); // Output: New York
In this example, name, age, and city are destructured from the person object and
assigned to variables with the same names.
Renaming Variables
You can rename variables while destructuring by using the : newVariableName
syntax.
let person = {
name: "Alice",
age: 25,
city: "Los Angeles"
};

let { name: firstName, age: years, city: location } = person;

[Link](firstName); // Output: Alice


[Link](years); // Output: 25
[Link](location); // Output: Los Angeles
In this example, the name property is assigned to firstName, age is assigned to
years, and city is assigned to location.
Default Values
You can assign default values to variables if the property doesn’t exist in the
object.
let person = {
name: "Bob",
age: 40
};

let { name, age, city = "Unknown" } = person;

[Link](city); // Output: Unknown


In this case, since the city property is missing in the person object, the default
value "Unknown" is assigned.
Nested Destructuring
You can destructure properties from nested objects by mirroring the structure of
the original object.
let person = {
name: "Chris",
address: {
street: "123 Main St",
city: "Miami"
}
};

let { name, address: { street, city } } = person;

[Link](street); // Output: 123 Main St


[Link](city); // Output: Miami
Here, we destructure the street and city properties from the address object
within person.
Destructuring with Functions
Object destructuring is often used when passing objects as arguments to
functions. This can make it easier to access specific properties without
referencing the whole object.
function printPerson({ name, age }) {
[Link](`Name: ${name}, Age: ${age}`);
}

let person = { name: "David", age: 45 };

printPerson(person); // Output: Name: David, Age: 45


You can also assign default values to destructured parameters in function
definitions:
function printPerson({ name, age, city = "Unknown" }) {
[Link](`Name: ${name}, Age: ${age}, City: ${city}`);
}
let person = { name: "Eve", age: 29 };

printPerson(person); // Output: Name: Eve, Age: 29, City: Unknown

Using Rest Operator with Destructuring


The rest operator (...) can be used to collect the remaining properties of an
object into another object.
let person = {
name: "Frank",
age: 35,
city: "Boston",
occupation: "Engineer"
};

let { name, age, ...rest } = person;

[Link](name); // Output: Frank


[Link](rest); // Output: { city: 'Boston', occupation: 'Engineer' }
In this example, name and age are destructured into their own variables, and the
remaining properties are grouped into the rest object.
Computed Property Names
You can dynamically assign a variable name using computed property names
with object destructuring.
let key = "age";
let person = {
name: "Grace",
age: 28
};
let { [key]: ageValue } = person;

[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 }
];

let [{ name: firstName }, { name: secondName }] = people;

[Link](firstName); // Output: Hank


[Link](secondName); // Output: Ivy
Here, the array people contains two objects, and we destructure the name
properties from both objects.

1. Creating JSON in JavaScript


JSON in JavaScript is created using objects or arrays. For example:
const jsonObject = {
"name": "John",
"age": 30,
"isStudent": false,
"address": {
"street": "123 Main St",
"city": "New York"
},
"courses": ["Math", "Science", "Literature"]
};
2. Converting JavaScript Objects to JSON
You can convert a JavaScript object into a JSON string using [Link]().
const obj = { name: "Alice", age: 25, city: "Los Angeles" };
const jsonStr = [Link](obj);
[Link](jsonStr); // {"name":"Alice","age":25,"city":"Los Angeles"}
3. Parsing JSON Strings into JavaScript Objects
You can convert a JSON string back to a JavaScript object using [Link]().
const jsonStr = '{"name":"Alice","age":25,"city":"Los Angeles"}';
const obj = [Link](jsonStr);
[Link]([Link]); // Alice
4. Accessing JSON Data
Once you have your data as a JavaScript object, you can access its properties
using dot notation or bracket notation.
const user = {
"name": "John",
"age": 30,
"skills": ["JavaScript", "Python", "C++"]
};

[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
}

function compute(callBack, x, y){


return callBack(x,y)
}

[Link](compute(add, 10, 5))


[Link](compute(divide, 10, 5))
Callbacks are great, but you don't want to use them excessively. If you do, you'll get something
called "callback hell". This happens when you nest callbacks within callbacks many levels
deep.

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

"Consuming code" is code that must wait for the result

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.

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


//do something
});
The Promise() constructor takes a function as an argument. The function also accepts two functions resolve() and
reject().

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.

// Executor function passed to the


// Promise constructor as an argument
function(resolve, reject) {
// Your logic goes here...
}
const count = true;

let countValue = new Promise(function (resolve,


reject) {
if (count) {
resolve("There is a count value.");
} else {
reject("There is no count value");
}
});

[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")
}
})

[Link]((e) => { [Link](e) });


[Link]((e) => { [Link](e) })
Async/await
The use of await, which halts execution until the promise is fulfilled, allows us to write
asynchronous functions as though they were synchronous (executed sequentially).
Async/await is a technique for building asynchronous code that looks and behaves like
synchronous code. It enables you to construct code that appears to run in sequence but
operates asynchronously.
Async simply allows us to write promises-based code as if it was synchronous and it checks
that we are not breaking the execution thread. It operates asynchronously via the event loop.
Async functions will always return a value.
Example:-
const getData = async () => {
let y = await "Hello World";
[Link](y);
}
[Link](1);
getData();
[Link](2);
// Example using async/await
const incrementDigits =a sync num=>{
num++; The async/await syntax is used in this code
[Link](num); fragment to increment a number until it reaches
if(num<10){
10. The async keyword, which comes before the
await incrementDigits(num);
}else{ declaration of the incrementDigits() function,
return'done!'; denotes that a
} promise will be returned by the function.
};
(async()=>{
const res =await incrementDigits(0);
[Link](res);
})();
Example:-
let promise = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('Promise resolved')}, 4000);
});

// async function
async function asyncFunc() {

// wait until the promise resolves


let result = await promise;

[Link](result);
[Link]('hello');
}

// calling the async function


asyncFunc();
Example:-
let promise = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve('Promise resolved')}, 4000);
});

async function asyncFunc() {


try {
// wait until the promise resolves
let result = await promise;

[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);
}

You might also like