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

JavaScript Notes

This document provides an overview of JavaScript, covering key concepts such as variables, data types, operators, conditionals, loops, functions, strings, arrays, and the Document Object Model (DOM). It explains how to declare variables using var, let, and const, the rules for naming variables, and the various data types available in JavaScript. Additionally, it discusses methods for manipulating strings and arrays, as well as how to interact with the DOM in web development.

Uploaded by

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

JavaScript Notes

This document provides an overview of JavaScript, covering key concepts such as variables, data types, operators, conditionals, loops, functions, strings, arrays, and the Document Object Model (DOM). It explains how to declare variables using var, let, and const, the rules for naming variables, and the various data types available in JavaScript. Additionally, it discusses methods for manipulating strings and arrays, as well as how to interact with the DOM in web development.

Uploaded by

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

JavaScript

Chapter 1 - Variables & Data Types


Variables are Containers for Storing Data
JavaScript Variables can be declared in 4 ways:

Automatically

Using var - var is a global variable

Using let - let is a scoped variable

Using const

x = 5;
var x = 5;
let x = 5;
const x = 5;

When to Use var, let, or const?


1. Always declare variables
2. Always use const if the value should not be changed
3. Always use const if the type should not be changed (Arrays and Objects)
4. Only use let if you can't use const

5. Only use var if you MUST support old browsers.

Variable naming rules


You can call a variable pretty much anything you like, but there are limitations. Generally,
you should stick to just using Latin characters (0-9, a-z, A-Z) and the underscore
character.

Don't use underscores at the start of variable names — this is used in certain
JavaScript constructs to mean specific things, so may get confusing.

Don't use numbers at the start of variables. This isn't allowed and causes an error.

Variables are case sensitive — so myage is a different variable from myAge .

JavaScript 1
One last point: you also need to avoid using JavaScript reserved words as your
variable names — by this, we mean the words that make up the actual syntax of
JavaScript! So, you can't use words like var , function , let , and for as variable names.
Browsers recognize them as different code items, and so you'll get errors.

JavaScript has 8 Datatypes


String , Number , Big int , Boolean , Undefined , Null , Symbol , Object.

let length = 16; // Numbers:


let color = "Yellow"; // Strings:
let x = true; // Booleans
let car; // Undefined
let x = BigInt("123456789012345678901234567890"); // BigInt:
const person =
{
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
}; // Objects

The typeof Operator


You can use the JavaScript typeof operator to find the type of a JavaScript variable.

let x = 5;
console.log(typeof x);

All primitive types, except null , can be tested by the typeof operator. typeof

null returns "object" , so one has to use === null to test for null .

Chapter 2 - Operators & Conditionals


There are different types of JavaScript operators:

Arithmetic Operators * Assignment Operators

Operator Description Operator Example Same As

+ Addition = x=y x=y

JavaScript 2
- Subtraction += x += y x=x+y

* Multiplication -= x -= y x=x-y

** Exponentiation (ES2016) *= x *= y x=x*y

/ Division /= x /= y x=x/y

Modulus (Division %= x %= y x=x%y


%
Remainder)
**= x **= y x = x ** y
++ Increment

-- Decrement

Comparison Operators * Logical Operators

Operator Description Operator Description

== equal to && logical and

=== equal value and equal type || logical or

!= not equal ! logical not

not equal value or not equal


!==
type

> greater than

< less than

>= greater than or equal to

<= less than or equal to

? ternary operator

Ternary Operators

// condition ? val1 : val2


const status = age >= 18 ? "adult" : "minor";

If else conditionals
The "if" statement in JavaScript is used to execute a block of code if a certain condition is
met. The "else" clause is used to execute a block of code if the condition is not met.

if (condition) {
// code to be executed if condition is true
} else {

JavaScript 3
// code to be executed if condition is false
}

Chapter 3 - Loops & Functions


Standard for loop

for (initialization; condition; increment/decrement) {


// code to be executed
}

for (let i = 1; i <= 10; i++) {


console.log(i);
}

This loop will print the numbers 1 through 10 to the console.

For-in loop
The for-in loop is used to iterate over the properties of an object. It has the following
syntax:

for (variable in object) {


// code to be executed
}

The variable is assigned the name of each property in the object as the loop iterates over
them.
Here's an example of a for-in loop that iterates over the properties of an object:

let person = {
name: "John",
age: 30,
job: "developer"
};

for (let key in person) {

JavaScript 4
console.log(key + ": " + person[key]);
}

This loop will print the following to the console:

name: John
age: 30
job: developer

For-of loop
The for-of loop is used to iterate over the values of an iterable object, such as an array or a
string. It has the following syntax:

// forof loop is best for arrays


for (variable of object) {
// code to be executed
}

The variable is assigned the value of each element in the object as the loop iterates over
them.
Here's an example of a for-of loop that iterates over the elements of an array:

let numbers = [1, 2, 3, 4, 5];


for (let iterator of numbers) {
console.log(iterator);
}

This loop will print the numbers 1 through 5 to the console.

Create a JavaScript Function


We can create a function in JavaScript using the function keyword:

function greet() {
console.log("Hello World!");
}

JavaScript 5
Function Call
greet();

Arrow Function Syntax


The syntax of the arrow function is:

let myFunction = (arg1, arg2, ...argN) => {


statement(s)
}

myFunction is the name of the function.

arg1, arg2, ...argN are the function arguments.

statement(s) is the function body.

Note: Arrow functions were introduced in ES6. Some browsers may not support the use of
arrow functions.
arrow function with parameters .

const addNumbers = (a, b) => {


a + b;
}
const result = addNumbers(5, 3);
console.log(result);

JavaScript 6
Chapter 4 - Strings & its Methods
A JavaScript string is zero or more characters written inside quotes.

let carName1 = "Volvo XC60"; // Double quotes


let carName2 = 'Volvo XC60'; // Single quotes

Quotes Inside Quotes


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

let answer1 = "It's alright";


let answer2 = "He is called 'Johnny'";

Template Strings
Templates were introduced with ES6 (JavaScript 2016).
Templates are strings enclosed in backticks (`This is a template string`).

Templates allow single and double quotes inside a string:

let text = `He's often called "Johnny"`;

Escape Characters
Because strings must be written within quotes, JavaScript will misunderstand this string:

let text = "We are the so-called "Vikings" from the north.";

The string will be chopped to "We are the so-called ".

To solve this problem, you can use an backslash escape character.


The backslash escape character ( \ ) turns special characters into string characters:

Code Result Description

\' ' Single quote

\" " Double quote

\\ \ Backslash

JavaScript 7
Methods
The length property returns the length of a string:

let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";


let length = text.length;

The at() method returns the character at a specified index (position) in a string.

const name = "W3Schools";


let letter = name.at(2);

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

split() take an argument and give us two strings one from the left of argument , and one
from the right of argument . we can use 0 for choosing the left string , and 1 for choosing
the right part .

// slice
let text = "Apple, Banana, Kiwi";
let part = text.slice(7, 13);

// split
let a "let_her_go-song";
let b = a.split("-")[0];
// output - let_her_go
let c = a.split("-")[1];
// output - song

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

let text1 = "Hello World!";


let text2 = text1.toUpperCase();

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

let text1 = "Hello World!";


let text2 = text1.toLowerCase();

JavaScript 8
concat() joins two or more strings:

let text1 = "Hello";


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

The trim() method removes whitespace from both sides of a string:

let text1 = " Hello World! ";


let text2 = text1.trim();

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

the replaceAll() method replace all values with another value , its syntax is same as
replace .

let text = "Please visit Microsoft!";


let newText = text.replace("Microsoft", "W3Schools");

Chapter 5 - Arrays & its Methods


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.

const cars = ["Saab", "Volvo", "BMW"];

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.

const cars = ["Saab", "Volvo", "BMW"];


let car = cars[0];

Modifying the Array Elements


Elements in an array can be modified by assigning a new value to their corresponding
index.

JavaScript 9
let courses = ["HTML", "CSS", "Javascript", "React"];
courses[1]= "Bootstrap";

Adding Elements to the Array


Elements can be added to the array using methods like push() and unshift().

let courses = ["HTML", "CSS", "Javascript", "React"];

// Add Element to the end of Array


courses.push("Node.js");

// Add Element to the beginning


courses.unshift("Web Development");

Removing Elements from an Array


Remove elements using methods like pop(), shift(), or splice().

The splice() method adds new items to an array.


The slice() method slices out a piece of an array.

let courses = ["HTML", "CSS", "Javascript", "React", "Node.js"];

// Removes and returns the last element


let lastElement = courses.pop();

// Removes and returns the first element


let firstElement = courses.shift();

// Removes 2 elements starting from index 1 and adds other element a


t that position
courses.splice(1, 2, "Lemon", "Kiwi");

Array Length
Get the length of an array using the length property.

JavaScript 10
let courses = ["HTML", "CSS", "Javascript", "React", "Node.js"];
let len = courses.length;

Iterating Through Array Elements


We can iterate array and access array elements using for and forEach loop.

let courses = ["HTML", "CSS", "JavaScript", "React"];


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

Array Concatenation
Combine two or more arrays using the concat() method. Ir returns new array conaining
joined arrays elements.

let courses = ["HTML", "CSS", "JavaScript", "React"];


let otherCourses = ["Node.js", "Expess.js"];
let concateArray = courses.concat(otherCourses);

Conversion of an Array to String


We have a builtin method toString() to converts an array to a string.

let courses = ["HTML", "CSS", "JavaScript", "React"];


console.log(courses.toString());

Array join() Method


The join() method also joins all array elements into a string.

It behaves just like toString() , but in addition you can specify the separator:

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


fruits.join(" and ");

sorting an Array

JavaScript 11
The sort() method sorts an array alphabetically:

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


fruits.sort();

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

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


fruits.reverse();

Chapter 6 - Array Iteration


JavaScript Array forEach()
The forEach() method calls a function (a callback function) once for each array element.

let arr = [1, 3, 54, 3, 6, 33];


arr.forEach((value, index, array) => {
console.log(value, index, array);
});

JavaScript Array map()


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

The map() method does not change the original array.

let arr = [1, 3, 54, 3, 6, 33];


let newArr = arr.map((e) => {
return e ** 2;
});
console.log(newArr);

JavaScript Array filter()

JavaScript 12
The filter() method creates a new array with array elements that pass a test.

This example creates a new array from elements with a value larger than 2:

let arr = [1, 3, 54, 3, 6, 33];


console.log(
arr.filter((e) => {
if (e > 2) return true;
else return false;
})
);

JavaScript Array.from()
The Array.from() method returns an Array object from any object with a length property or
any iterable object.

// getting array from a string


Array.from("ABCDEFG");

// getting array from a number


let a=5;
let arr = Array.from(Array(number).keys());
// Output
1,2,3,4,5

JavaScript Array reduce()


The reduce() method runs a function on each array element to produce (reduce it to) a
single value.

The reduce() method works from left-to-right in the array.

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


let sum = numbers.reduce(myFunction);
function myFunction(total, value, index, array) {
return total + value;
}

JavaScript 13
Chapter 7 - DOM & User Interaction
DOM Nodes
According to the W3C HTML DOM standard, everything in an HTML document is a node:

The entire document is a document node

Every HTML element is an element node

The text inside HTML elements are text nodes

Every HTML attribute is an attribute node (deprecated)

All comments are comment nodes

With the HTML DOM, all nodes in the node tree can be accessed by JavaScript.
New nodes can be created, and all nodes can be modified or deleted.

Node Relationships
The nodes in the node tree have a hierarchical relationship to each other.

The terms parent, child, and sibling are used to describe the relationships.

In a node tree, the top node is called the root (or root node)

Every node has exactly one parent, except the root (which has no parent)

A node can have a number of children

Siblings (brothers or sisters) are nodes with the same parent

Navigating Between Nodes


You can use the following node properties to navigate between nodes with JavaScript:

parentNode

JavaScript 14
childNodes[ nodenumber ]

firstChild

lastChild

nextSibling

previousSibling

DOM Root Nodes


There are two special properties that allow access to the full document:

document.body - The body of the document

document.documentElement - The full document

JavaScript Interaction With User


Javascript allows us the privilege to which we can interact with the user and respond
accordingly. It includes several user-interface functions which help in the interaction. Let’s
take a look at them one by one.

JavaScript Window alert() Method :


It simply creates an alert box that may or may not have specified content inside it, but it
always comes with the ‘OK’ button. It simply shows a message and pauses the execution
of the script until you press the ‘OK’ button. The mini-window that pops up is called the
‘modal window’.

alert('HI there');

JavaScript Window prompt() Method:


Prompt is another user-interface function that normally contains two arguments.

let age = prompt('How old are you?');

The text is basically what you want to show the user and the default value argument is
optional though it acts like a placeholder inside a text field. It is the most used interface as
with it you can ask the user to input something and then use that input to build something.

JavaScript Window confirm() Method:

JavaScript 15
The confirm function basically outputs a modal window with a question and two buttons
‘OK’ and ‘CANCEL’.

let isHappy = confirm('Are you Happy?');

Chapter 8 - Targeting the Elements


innerHTML
The innerHTML property is a part of the JavaScript HTMLElement object and it allows
developers to access and manipulate the HTML content of an element.
The innerHTML property is a powerful tool for manipulating the HTML content of an element.
Developers can use it to add, remove, or replace elements, as well as change the text and
attributes of existing elements.

For example, consider the following HTML code:

<div id="myDiv">
<p>This is my paragraph</p>
<p>This is my paragraph</p>
</div>

let myDiv = document.getElementById("myDiv");


myDiv.innerHTML = "<p>This is my new text</p>";

outerHTML
The outerHTML property is a part of the JavaScript HTMLElement object and it allows
developers to access and manipulate the entire HTML of an element, including the
element's own tags.

The main difference between outerHTML and innerHTML is that outerHTML allows you to
change the entire element, including its own tags, whereas innerHTML only allows you to
change the content within the element .The outerHTML property returns the entire HTML of
an element, as a string of HTML .
For example, consider the following HTML code:

JavaScript 16
<div id="myDiv">
<p>This is my paragraph</p>
<p>This is my paragraph</p>
</div>

let myDiv = document.getElementById("myDiv");


myDiv.outerHTML = "<div><p>This is my new text</p></div>";

getElementsById
One of the most commonly used methods of the document object is
the getElementById() method. This method allows developers to access a specific element
on the web page by its unique ID . The getElementById() method is a convenient way to
access a specific element on a web page, as it saves developers from having to traverse
the entire DOM tree to find the element. This method is especially useful when working
with large and complex web pages, as it allows developers to quickly and easily access the
elements they need.
For example, consider the following HTML code:

<div id="myDiv">This is my div</div>

let myDiv = document.getElementById("myDiv");


myDiv.innerHTML = "This is my new text";

getElementsByClassName
This method is a part of the JavaScript document object and it allows developers to access
multiple elements on a web page by their class name. This method returns a live
HTMLCollection of elements with the given class name, or an empty HTMLCollection if no
such elements are found . This method is especially useful when working with large and
complex web pages, as it allows developers to quickly and easily access multiple elements
that share the same class name.
For example, consider the following HTML code :

<div class="myClass">This is my div</div>


<div class="myClass">This is my div</div>

JavaScript 17
<div class="myClass">This is my div</div>

let elements = document.getElementsByClassName("myClass");


for (let i = 0; i < elements.length; i++) {
elements[i].innerHTML = "This is my new text";
}

getElementsByTagName
The getElementsByTagName() method is a part of the JavaScript document object and it allows
developers to access multiple elements on a web page by their HTML tag name. This
method returns a live HTMLCollection of elements with the given tag name, or an empty
HTMLCollection if no such elements are found.
For example, consider the following HTML code:

<p>This is my paragraph</p>
<p>This is my paragraph</p>
<p>This is my paragraph</p>

let elements = document.getElementsByTagName("p");


for (let i = 0; i < elements.length; i++) {
elements[i].innerHTML = "This is my new text";
}

querySelector()
The querySelector() is a method used for searching and returning the very first
element within the document that matches the given selector. The queryselector in
javascript only returns the element that matches with one of the specified CSS selectors,
or a group of selectors. However, if no matches are found, it returns null.

document.querySelector(".box2").style.backgroundColor = "green";

querySelectorAll()
Since querySelector() in javascript returns only a single element, the additional
querySelectorAll() method can be used in situations where you need to get all matching

JavaScript 18
selector elements in the document.

document.querySelectorAll(".box").forEach((e) => {
e.style.backgroundColor = "yellow";
});

Chapter 9 - Insertion, Attributes & Class


Methods
Attribute methods
So, if an attribute is non-standard, there won’t be a DOM-property for it. Is there a way to
access such attributes?

Sure. All attributes are accessible by using the following methods:

elem.hasAttribute(name) – checks for existence.

elem.getAttribute(name) – gets the value.

elem.setAttribute(name, value) – sets the value.

elem.removeAttribute(name) – removes the attribute.

These methods operate exactly with what’s written in HTML.


Also one can read all attributes using elem.attributes : a collection of objects that belong to
a built-in Attr class, with name and value properties.

<div class="container">
<div style="border: 2px solid black" class="box"></div>
</div>
<script>
let e = document.querySelector(".box");

e.hasAttribute("style");
// true

e.hasAttribute("id");
// false

e.getAttribute("style");

JavaScript 19
// 'border: 2px solid black'

e.removeAttribute("style");
// style will be removed

e.setAttribute("id", "hero");
// id has been setted

e.setAttribute("style", "border:2px solid black");


// style has been added

e.attributes;
// NamedNodeMap {0: class, 1: id, 2: style, class: class, id:
id, style: style, length: 3}
</script>

Append Methods
Sure. All attributes are accessible by using the following methods:

node.append(element) – insert at the end of the node .

node.prepend(element) – insert at the beginning of the node .

node.before(element) – insert before the node .

node.after(element) – insert after the node .

node.replaceWith(element) - replace node with the given node .

Creating New HTML Elements (Nodes)


To add a new element to the HTML DOM, you must create the element (element node)
first, and then append it to an existing element .

<div class="container">
<div class="box">box 1</div>
<div class="box">box 2</div>
</div>
<script>
// adding elements to html page
let div = document.createElement("div");
div.innerHTML = "box 3";

JavaScript 20
div.setAttribute("class", "box");
let cont = document.querySelector(".container");
cont.append(div);
</script>

Removing Existing HTML Elements


To remove an HTML element, use the remove() method:

<div>
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
const elmnt = document.getElementById("p1"); elmnt.remove();
</script>

Replacing HTML Elements


To replace an element to the HTML DOM, use the replaceChild() method:

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
const para = document.createElement("p");
const node = document.createTextNode("This is new.");
para.appendChild(node);
const parent = document.getElementById("div1");
const child = document.getElementById("p1");
parent.replaceChild(para, child);
</script>

Insert Adjacent HTML


The insertAdjacentHTML() method inserts HTML code into a specified position.

JavaScript 21
Legal positions:

Value Description

afterbegin After the beginning of the element (first child)

afterend After the element

beforebegin Before the element

beforeend Before the end of the element (last child)

const h2 = document.getElementById("myH2");
let html = "<p>My new paragraph.</p>";
h2.insertAdjacentHTML("afterend", html);

the .className Property


Using the .className property is the most straightforward and default way. We can
use .className to add a class in javascript; we can also get the name of any pre-existing
class.

The .className can also be used to add multiple classes to an element.

el.className = "new-class";

Property -

newClass: Here, you need to add the new class name inside double quotes. We can
also add multiple class names by giving space after each new class name.

el.className = "class1 class2 class3";

classList Property?
The Classlist in JavaScript property allows you to powerfully manipulate the classes(the
group of HTML elements) attached to an HTML Element. You might have seen the like
button on many websites where you click on the like button it shows thumbs up otherwise
thumbs down, it is known as the toggle effect. To do so we have to change the class name
of the element and it can be done using the classList toggle method. You can also use
JavaScript classList property to add, remove, toggle, check if an element has a specified
class, and even replace classes on an element.

JavaScript 22
element.classList

The element here is an HTML element that has a class and to get the name of the
class .classList is used.

Toggle a Class
The toggle() method removes the CSS class from the class list of the element if the
specified CSS class is present, if the specified CSS class is not present then it adds the
CSS class.

element.classList.toggle('classname')

Suppose we created a website that has a switch to change the theme of the page. To do
that we will use the toggle method where if the entered class is not present in the element
then it will add the light-theme class entered in the toggle method. In the following
example, we are using the toggle() method to toggle for the division CSS class from the
element id section1.

Chapter 10 - Browser Events


The setTimeout() Method
Executes a function, after waiting a specified number of milliseconds . ( only one time )
setTimeout( function , milliseconds );

The first parameter is a function to be executed.

The second parameter indicates the number of milliseconds before execution.

setTimeout(() => {
alert("error");
}, 5000);

How to Stop the Execution?


The clearTimeout() method stops the execution of the function specified in setTimeout().

clearTimeout( timeoutVariable ) . The clearTimeout() method uses the variable returned


from setTimeout() :

JavaScript 23
myVar = setTimeout(function, milliseconds);
clearTimeout(myVar);

If the function has not already been executed, you can stop the execution by calling
the clearTimeout() method:

The setInterval() Method


The setInterval() method repeats a given function at every given time-interval
continuously .
setInterval( function , milliseconds );

The first parameter is the function to be executed.

The second parameter indicates the length of the time-interval between each execution.

setInterval(() => {
let x = Math.floor(Math.random() * 255 + 1);
let y = Math.floor(Math.random() * 255 + 1);
let z = Math.floor(Math.random() * 255 + 1);
document.body.style.backgroundColor = `rgb(${x},${y},${z})`;
}, 5000);

How to Stop the Execution?


The clearInterval() method stops the executions of the function specified in the
setInterval() method. - clearInterval( timerVariable )

The clearInterval() method uses the variable returned from setInterval() :

let myVar = setInterval(function, milliseconds);


clearInterval(myVar);

The addEventListener() method


The addEventListener() method attaches an event handler to an specified element without
overwriting existing event handlers . You can add many event handlers of the same type to
one element, i.e two "click" events . You can add event listeners to any DOM object not
only HTML elements. i.e the window object.
The addEventListener() method makes it easier to control how the event reacts to bubbling.

JavaScript 24
element.addEventListener(event, function);

The first parameter is the type of the event (like " click " or " mousedown " or any other HTML
DOM Event.)
The second parameter is the function we want to call when the event occurs.

// Example
let button = document.querySelector("#btn");
button.addEventListener("click", () => {
let inner = document.querySelector(".box");
inner.innerHTML = "bye bye";
});

Note that you don't use the "on" prefix for the event; use " click " instead of " onclick ".

The removeEventListener() method


The removeEventListener() method removes event handlers that have been attached with the
addEventListener() method:

element.removeEventListener("mousemove", myFunction);

Mouse Events
Event Occurs When

onclick A user clicks on an element

oncontextmenu A user right-clicks on an element

ondblclick A user double-clicks on an element

onmousedown A mouse button is pressed over an element

onmouseenter The mouse pointer moves into an element

onmouseleave The mouse pointer moves out of an element

onmousemove The mouse pointer moves over an element

onmouseout The mouse pointer moves out of an element

onmouseover The mouse pointer moves onto an element

onmouseup A mouse button is released over an element

JavaScript 25
Clipboard Events
Attribute Value Description

Fires when the user copies the content of an


oncopy script
element

oncut script Fires when the user cuts the content of an element

Fires when the user pastes some content in an


onpaste script
element

Chapter 11 - Callback and Promises


A callback function in javascript is a function that is passed as an argument in another
function. Which is then called inside the parent function to complete a routine or an action.
To put it more simply, it is a function that will be called(executed) later after its parent
function(the function in which it is passed as an argument) is done executing.

Let's see an example :

function sum(a, b) {
console.log(a + b)
}
function operation(val1, val2, callback) {
callback(val1, val2)
}
operation(6, 5, sum)

Output : 11

In the above code, we can see in the function operation the third parameter is a callback
function. We are first passing the "callback" as an argument and then calling it inside the
parent function 𝑖.𝑒.i.e., operation. Here, we have taken the "sum" as the callback function,
we can create any function and pass it as the callback in the operation function.

1. Synchronous Callback Function


In general, synchronous programming has the following two features :

A single task is executed at a time.

The next set of following tasks will only be addressed once the current task gets
finished. Thereby following a sequential code execution.

JavaScript 26
console.log('Start')
function divide(a, b) {
console.log(a / b)
}
function operation(val1, val2, callback) {
callback(val1, val2)
}
operation(16, 4, divide)
console.log('End')

Output :

Start
4
End

2. Asynchronous Callback Function

console.log('Start')
setTimeout(() => {
console.log('We are in the setTimeout()')
}, 4000)
console.log('End')

Output :

Start
End
We are in the setTimeout()

The execution of this code is different than what we are used to(synchronous).

Callback Hell
The phenomenon which happens when we nest multiple callbacks within a function is
called a callback hell. The shape of the resulting code structure resembles a pyramid and
hence callback hell is also called the “pyramid of the doom”. It makes the code very
difficult to understand and maintain. It is most frequently seen while working with Node.js.
The code below shows an example of a callback hell.

JavaScript 27
Promises
A promise is an object with a syntactical coating introduced by ES6 which became another
way of skipping writing callbacks to implement asynchronous operations. Web APIs like
fetch() are implemented using the promising methodology. It makes the code more
readable and is a solution to escape the callback hell.

Unlike synchronous functions, asynchronous functions may not return a value immediately.
Hence, these asynchronous functions instead return a Promise() which can be later used
to get the final value when it gets available in the future. We can easily handle situations
where we successfully receive the data using the resolve() or where we fail to get the data
due to some network error, timeout etc using the reject() as shown below.

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


// asynchronous call is made// resolve or reject the data
});

A promise has four states :

Pending

Settled

Fulfilled

Rejected

Using these different states a promise does efficient error handling.

When the action related to the promise is neither fulfilled nor rejected, it's in a
pending state.

When the action related to the promise is either fulfilled or rejected, it's in a settled
state.

JavaScript 28
When the action related to the promise is executed successfully(resolved), it's in
the fulfilled state.

When the action related to the promise fails(not resolved) due to some error, it's in
the rejected state.

Using the .then() method we can do further actions like calling another callback
function or catching the error.

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


let a = Math.random();
if (a > 0.5) reject("new error");
else resolve("accepted");
});
prom1
// .then is evoked when it is resolve
.then((e) => {
console.log(e);
})
// .catch is evoked when it is reject
.catch((e) => {
console.log(e);
});

Promise API
There are 6 static methods in the Promise class. We’ll quickly cover their use cases here.

Promise.all
Let’s say we want many promises to execute in parallel and wait until all of them are ready.

For instance, download several URLs in parallel and process the content once they are all
done.

That’s what Promise.all is for.

Promise.allSettled
Promise.allSettled just waits for all promises to settle, regardless of the result. The resulting
array has:

{status:"fulfilled", value:result} for successful responses,

JavaScript 29
{status:"rejected", reason:error} for errors.

Promise.race
Similar to Promise.all , but waits only for the first settled promise and gets its result (or
error).

Promise.any
Similar to Promise.race , but waits only for the first fulfilled promise and gets its result. If all
of the given promises are rejected, then the returned promise is rejected
with AggregateError – a special error object that stores all promise errors in
its errors property.

Promise.resolve/reject
Methods Promise.resolve and Promise.reject are rarely needed in modern code,
because async/await syntax (we’ll cover it a bit later) makes them somewhat obsolete.

JavaScript Async/Await
"async and await make promises easier to write"
async makes a function return a Promise

await makes a function wait for a Promise

Async Syntax
The keyword async before a function makes the function return a promise:

async function myFunction() {


return "Hello";
}

Await Syntax
The await keyword can only be used inside an async function.

The await keyword makes the function pause the execution and wait for a resolved
promise before it continues:

let value = await promise;

JavaScript 30
Using Async Await
async function getdata() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(5);
}, 5000);
});
}
async function main() {
console.log("data processing ");
let data = await getdata();
console.log(data);
console.log("data is ready");
}
main();

Chapter 12 - Error Handling


Exception handling in Javascript is the process of handling abnormal statements that occur
during the execution of a program.

And it also helps in tracking errors, which means that the exception explains why the error
occurred and when and where it happened in the code.

Types of Errors
1. Syntax Error:- Syntax errors appear when the user makes a mistake in the predefined
syntax of the javascript language. The interpreter cannot interpret this error raised during
the code compilation.

2. Runtime Error:- Runtime Error occurs during the program's execution and gets detected
only when you run the program; that's why it's known as a runtime error. And these errors
suddenly crash the program or applications, and that's where exception handling became
useful, and via the help of it, we can maintain the normal flow of the program.
3. Logical Error:- Logical Error occurs when there is any logical mistake in the program
that may not produce the desired output and may terminate abnormally. These types of
errors do not throw an error message or an exception.

Error Object

JavaScript 31
Whenever an error occurs during the execution or runtime of the program, the code stops
unexpectedly, and JavaScript raises an exception scenario with the Error object thrown by
the throw statement.
The error object is thrown by JavaScript, or the user can create a user-defined error object
with the help of the throw statement.

The error object has two main properties:

name:- error name stores or returns the name of the error.

Message:- Whereas error message gives or describes the error message in string
form in JavaScript.

// syntax - throw error-name("message")


throw SyntaxError("its a syntax error");

Exception Handling Statements


An exception is an abnormal or unexpected condition that occurs during the runtime, and
javascript provides various statements or a combination of statements to handle the
exceptions.

It handles exceptions in try-catch-finally statements and throws statements.


Before we explore each statement, let's get a basic understanding of these terms:

try{}:- The try block will contain the code, which may cause exceptions during the
execution. If any errors occur, It stops the execution immediately and passes the
control to the catch block.

catch{}:- The catch block contains the code that will only execute when the errors
occur in the corresponding try block. If the try block is executed successfully, then the
catch block will be ignored.

try {
// code
} catch (err) {
// code
}

finally{}:- The code placed inside the "finally" block will be executed whether an error
has occurred or not.

JavaScript 32
Point - finally is very useful in function , because in a function if we had a return statement
then our rest of the code after it will not run , but if we use finally then we can do this .

throw:- The throw keyword or statement is used for throwing custom or user-defined
errors.

JavaScript 33

You might also like