Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
40 views

Java Script Part 2 PPT-Unit2 MSD

Uploaded by

P.Padmini Rani
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Java Script Part 2 PPT-Unit2 MSD

Uploaded by

P.Padmini Rani
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 171

JAVA SCRIPT

(Cont..)
FUNCTIONS IN JAVASCRIPT
 The JavaScript engine can execute JavaScript code in
two different modes:
 Immediate mode
 As soon as the webpage loads on the browser,
JavaScript code embedded inside it, executes
without any delay.
 Deferred mode
 Execution of JavaScript code is deferred or delayed
until any user action like data input, button
click, drop-down selection, etc. takes place.
 In immediate mode, As soon as the page is loaded in
the browser, the script gets executed line by line
without any delay.
 But in real-world application development, it is not
possible to wait for sequential execution of the code
written for the huge applications.
 A JavaScript function is a set of statements that
performs a specific task. They become a reusable unit
of code.
 In JavaScript, functions are first-class objects. i.e.,
functions can be passed as an argument to other
functions, it can be a return value of another function
TYPES OF FUNCTIONS
 JavaScript has two types of functions.

1. User-defined functions

The user-defined functions can also be created


using a much simpler syntax called arrow
functions.

2. Built-in functions

Predefined functions that perform tasks such as


displaying dialog boxes, parsing a string argument,
timing-related operations, and so on.
FUNCTION DECLARATION AND FUNCTION
INVOCATION
 To use a function, it must be defined or declared and
then it can be invoked anywhere in the program.
 A function declaration also called a function definition,
consists of the function keyword, followed by:

Syntax for Function Declaration:

function function_name(parameter 1, parameter 2 , …,


parameter n) {

//statements to be executed

}
Example:

function multiply(num1, num2) {

return num1 * num2;

}
 The code written inside the function body will be
executed only when it is invoked or called.

Syntax for Function Invocation:

function_name(argument 1, argument 2, ..., argument


n);

Example:
 multiply (5,6);
ARROW FUNCTION
 In JavaScript, functions are first-class objects, i.e
you can assign a function as a value to a variable.
For example,
let sayHello = function () {
console.log("Welcome to JavaScript");
};
sayHello();
 Here, a function without a name is called
an anonymous function which is assigned to a
variable sayHello.
 JavaScript has introduced a new and concise way

of writing functions using arrow notation. The arrow


function is one of the easiest ways to declare an
anonymous function.
Example:

let sayHello = () => {

console.log("Welcome to JavaScript");

};

sayHello();

There are two parts for the Arrow function syntax:

1. let sayHello = ()
 This declares a variable sayHello and assigns a function
to it using () to just say that the variable is a function.

2. => { }
 This declares the body of the function with an arrow and
the curly braces.
 Below are a few scenarios of arrow functions.

Syntax 1: Multi-parameter, multi-line code:


 If code is in multiple lines, use { }.

calculateCost = (ticketPrice,
noOfPerson)=>{ noOfPerson= ticketPrice *
noOfPerson;

return noOfPerson;

console.log(calculateCost(500, 2));

// 1000
 Syntax 2: No parameter, single line code:
 If the code is single line, { } is not required. The
expression is evaluated and automatically returned.

trip = () => “Let's go to trip.”

console.log(trip());

// Let's go to trip.
 Syntax 3: One parameter, single line code:
 If only one parameter, then () is not required.

trip = place => "Trip to " + place;

console.log(trip("Paris"));

// Trip to Paris
 Syntax 4: One parameter, single line
code:
 if only one parameter, use '_' and do not use a
variable name also.

trip = _ => "Trip to " + _;

console.log(trip("Paris"));

// Trip to Paris
'THIS' KEYWORD IN ARROW
FUNCTION
 we can not use ’this’ keyword directly into arrow
function because it does not contain its
own ’this’ . So when we use this keyword in the
arrow function, it will return an undefined value.
 So to resolve this issue we need to
bind this keyword into this arrow function
like below.
FUNCTION PARAMETERS
 Function parameters are the variables that
are defined in the function definition and the
values passed to the function when it is
invoked are called arguments.
 In JavaScript, function definition does not
have any data type specified for the
parameters, and type checking is not
performed on the arguments passed to the
function.
 JavaScript does not throw any error if the number of
arguments passed during a function invocation
doesn’t match with the number of parameters
listed during the function definition.
 If the number of parameters is more than the

number of arguments, then the parameters that


have no corresponding arguments are set to
undefined.
 function multiply(num1, num2) {

if (num2 == undefined) {
num2 = 1; }
return num1 * num2;
}
console.log(multiply(5, 6)); // 30
console.log(multiply(5)); // 5
DEFAULT PARAMETERS
 JavaScript introduces an option to assign default values in
functions.

function multiply(num1, num2 = 1) {

return num1 * num2;

console.log(multiply(5, 5)); //25

console.log(multiply(10)); //10

console.log(multiply(10, undefined)); //10


 In the above example, when the function is invoked with two
parameters, the default value of num2 will be overridden
and considered when the value is omitted while calling.
REST PARAMETERS
 Rest parameter syntax allows to hold an
indefinite number of arguments in the form of an
array.

Syntax:

function(a, …args) {

//…

}
 The rest of the parameters can be included in the
function definition by using three dots ( … )
followed by the name of the array that will hold
Example:

function showNumbers(x, y, …z) {

return z;

console.log(showNumbers(1, 2, 3, 4, 5)); //
[3,4,5]

console.log(showNumbers(3, 4, 5, 6, 7, 8, 9,
10));

// [5,6,7,8,9,10]
 The rest parameter should always be the last
DESTRUCTURING
ASSIGNMENT
 Which makes it easy to unpack values from arrays,
or properties from objects, into different variables.
 Array destructuring in functions

 Example:

let myArray = ["Andrew", "James", "Chris"];


function showDetails([arg1, arg2]) {
console.log(arg1); // Andrew
console.log(arg2); // James
}
showDetails(myArray);
 In the above example, the first two array elements

‘Andrew’ and 'James’ have been destructured into


individual function parameters arg1 and arg2.
OBJECT RESTRUCTURING IN
FUNCTIONS
 Example:

let myObject = { name: "Mark", age: 25, country:


"India" };

function showDetails({ name, country }) {


console.log(name, country);

// Mark India

showDetails(myObject);
 The properties name and country of the object have

been destructured and captured as a function parameter.


NESTED FUNCTION
 The function within another function body is called a nested
function.
 The nested function is private to the container function and

cannot be invoked from outside the container function.


Example:
function giveMessage(message) {
let userMsg = message;
function toUser(userName) {
let name = userName;
let greet = userMsg + " " + name;
return greet;
}
userMessage = toUser("Bob");
return userMessage;
}
console.log(giveMessage("The world says hello dear: "));
// The world says hello dear: Bob
BUILT - IN FUNCTIONS
Built-in
Description Example
functions
It throws an alert box and is often
used when user interaction is required alert("Let us
alert()
to decide whether execution should proceed");
proceed or not.
It throws a confirm box where user
let decision =
can click "OK" or "Cancel". If "OK"
confirm() confirm("Shall we
is clicked, the function returns "true",
proceed?");
else returns "false".
Built-in
Description Example
functions
It produces a box where user can
enter an input. The user input may
let userInput =
be used for some processing later.
prompt() prompt("Please
This function takes parameter of
enter your name:");
type string which represents the
label of the box.
This function checks if the data-
type of given parameter is number isNaN(30); //false
isNaN()
or not. If number, it returns isNaN('hello'); //true
"false", else it returns "true".
Built-in
Description Example
functions
It determines if the number
given as parameter is a
finite number. If the isFinite(30);
parameter value is NaN, //true
isFinite()
positive infinity, or negative isFinite('hello');
infinity, this method will //false
return false, else will return
true.
eval("let num1=2;
It takes an argument of type
let num2=3;
string which can be an
let result= num1 *
eval() expression, statement or
num2;
sequence of statements and
evaluates them. console.log(result)"
);
Built-in
Description Example
functions
This function parses string and parseInt("10"); //10
returns an integer number.
parseInt("10 20
It takes two parameters. The first 30");
parameter is the string to be parsed. //10, only the
The second parameter represents integer part is
radix which is an integer between 2 returned

parseInt() and 36 that represents the numerical


parseInt("10
system to be used and is optional. years");
The method stops parsing when it //10
encounters a non-numerical character
parseInt("years
and returns the gathered number. 10");
It returns NaN when the first non- //NaN, the first
whitespace character cannot be character stops the
parsing
converted to number.
Built-in
Description Example
functions
This function parses string and parseFloat("10.34"
returns a float number. ); //10.34
The method stops parsing when parseFloat("10 20
it encounters a non-numerical 30");
parseFloat(
character and further characters
) //10
are ignored.
parseFloat("10.50
It returns NaN when the first non- years");
whitespace character cannot be
converted to number. //10.50
JAVASCRIPT PROVIDES TWO-TIMER BUILT-IN FUNCTIONS.
Built-in functions Description Example

It executes a given function function executeMe(){


after waiting for the console.log("Function
specified number of says hello!")
milliseconds.
}
setTimeout() It takes 2 parameters. First is
the function to be executed setTimeout(executeMe
and the second is the , 3000);
number of milliseconds after //It executes
which the given function executeMe() after 3
should be executed. seconds.
Built-in
Description Example
functions

It cancels a timeout previously


function executeMe(){
established by calling
setTimeout(). console.log("Function
says hello!")
It takes the parameter
"timeoutID" which is the }
clearTimeout()
identifier of the timeout that let timerId=
can be used to cancel the setTimeout(executeMe
execution of setTimeout(). The , 3000);
ID is returned by the
clearTimeout(timerId);
setTimeout().
Built-in
Description Example
functions

function executeMe(){
It executes the given function
repetitively. console.log("Function
says hello!");
It takes 2 parameters, first is
the function to be executed }
setInterval() and second is the number of setInterval(executeMe,
milliseconds. The function 3000);
executes continuously after
//It executes
every given number of
executeMe() every 3
milliseconds.
seconds
Built-in
Description Example
functions

function executeMe(){
console.log("Function says
hello!");}
let timerId=
It cancels the timed, repeating
setInterval(executeMe, 2000);
execution which was previously
established by a call to setInterval(). function stopInterval(){

clearInterval() It takes the parameter “intervalID” clearInterval(timerId);


which is the identifier of the timeout
console.log("Function says
that can be used to cancel the
bye to setInterval()!")
execution of setInterval(). The ID is
returned by the setInterval(). setTimeout(stopInterval,5000)
//It executes executeMe()
every 2 seconds and after 5
seconds, further calls to
executeMe() is stopped.
VARIABLE SCOPE IN FUNCTIONS
 Scopes
 Variable declaration in the JavaScript program can be
done within the function or outside the function. But the
accessibility of the variable to other parts of the same
program is decided based on the place of its declaration.
This accessibility of a variable is referred to as scope.

JavaScript scopes can be of three types:


 Global scope
 Local scope
 Block scope
GLOBAL SCOPE
//Global variable

var greet = "Hello JavaScript";

function message() {

//Global variable accessed inside the function

console.log("Message from inside the function: " + greet);

message();

//Global variable accessed outside the function

console.log("Message from outside the function: " + greet);

//Message from inside the function: Hello JavaScript

//Message from outside the function: Hello JavaScript


LOCAL SCOPE
 Variables declared inside the function would have local
scope. These variables cannot be accessed outside the
declared function block.
Example:
function message() {
//Local variable
var greet = "Hello JavaScript";
//Local variables are accessible inside the function
console.log("Message from inside the function: " + greet);
}
message();
//Local variable cannot be accessed outside the function
console.log("Message from outside the function: " +
greet);
//Message from inside the function: Hello JavaScript
//Uncaught ReferenceError: greet is not defined
 If a local variable is declared without the use of
keyword 'var', it takes a global scope.
Example:
//Global variable
var firstName = "Mark";
function fullName() {
//Variable declared without var has global scope
lastName = "Zuckerberg";
console.log("Full Name from inside the function: " +
firstName + " " + lastName);
}
fullName();
console.log("Full Name from outside the function: " +
firstName + " " + lastName);
//Full Name from inside the function: Mark Zuckerberg
//Full Name from outside the function: Mark Zuckerberg
BLOCK SCOPE
 In 2015, JavaScript introduced two new keywords to
declare variables: let and const.
 Variables declared with 'var' keyword are function-

scoped whereas variables declared with 'let' and


'const' are block-scoped and they exist only in the
block in which they are defined.
Example:
function testVar() {
if (10 == 10) {
var flag = "true";
}
console.log(flag); //true
}
testVar();
 In the above example, the variable flag declared inside

'if' block is accessible outside the block since it has


 Modifying the code to use 'let' variable will result
in an error:
function testVar() {
if (10 == 10) {
let flag = "true";
}
console.log(flag);
//Uncaught ReferenceError: flag is not defined
}
testVar();
 The usage of 'let' in the above code snippet has

restricted the variable scope only to 'if' block.


 'const' has the same scope as that of 'let' i.e.,

block scope.
HOISTING
 Hoisting means all the variable and function declarations
wherever they are present throughout the program, gets
lifted and declared to the top of the program.
 Only the declaration and not the initialization gets hoisted
to the top.
 If a variable is tried to access without declaration, the
Reference Error is thrown.
 Let us declare and initialize the variable in the code but
after it is accessed.
console.log("First name: "+firstName);
//First name: undefined
var firstName = "Mark";
 Because of Hoisting, the code is interpreted as below by the
interpreter:
var firstName;
console.log("First name: "+firstName);
// First name: undefined
 Hoisting here helps interpret to find the
declaration at the top of the program and thus
reference error goes away.
 But interpreter says that the variable is not

defined. This is because hoisting only lifted the


variable declaration on the top and not
initialization.
 Variables declared using 'let' and 'const' are not

hoisted to the top of the program.


Example:
 console.log("First name: "+firstName);

 let firstName = "Mark";

 The above code throws an error as ”Uncaught

ReferenceError: Cannot access 'firstName'


before initialization”
WORKING WITH CLASSES
 In 2015, JavaScript introduced the concept of the
Class.
 Classes and Objects in JavaScript coding can be

created similar to any other Object-


Oriented language.
 Classes can also have methods performing

different logic using the class properties


respectively.
 The new feature like Class and Inheritance eases

the development and work with Classes in the


application.
 JavaScript is an object-based language and

allows to create hierarchies of objects and to


have inheritance of properties and their values.
CREATING AND INHERITING CLASSES
 Creating Classes:
 In 2015, ECMAScript introduced the concept of classes
to JavaScript.
 The keyword class is used to create a class.
 The constructor method is called each time the class
object is created and initialized.
 The Objects are a real-time representation of any entity.
 Different methods are used to communicate
between various objects, to perform various operations.
Example: A calculator accepting two numbers to do
addition and subtraction operations.
class Calculator {
constructor(num1, num2){
// Constructor used for initializing the class instance
/* Properties initialized in the constructor */
this.num1 = num1;
this.num2 = num2;
}
/* Methods of the class used for performing operations */
add() {
return this.num1 + this.num2;
}
subtract() {
return this.num1 - this.num2;
}
}
let calculator = new Calculator(300, 100);

// Creating Calculator class object or instance

console.log("Add method returns" +


calculator.add()); // Add method returns 400.

console.log("Subtract method returns" +


calculator.subtract());

// Subtract method returns 200.


CLASS - STATIC METHOD
 Static methods can be using the static . Static values
can be accessed only using the class name and not
using 'this' keyword. Else it will lead to an error.
 Example: display() is a static method and it is accessed

using the class name.


class Calculator {
constructor(num1, num2) {
// Constructor used for initializing the class instance
/* Properties initialized in the constructor */
this.num1 = num1;
this.num2 = num2;
}
/* static method */
static display() {
console.log("This is a calculator app");
}
/* Methods of the class used for performing
operations */
add() {
return this.num1 + this.num2;
}
subtract() {
return this.num1 - this.num2;
}
}
/*static method display() is invoked using class name
directly. */
Calculator.display();

The output of the above code is :


This is a calculator app
INHERITING CLASSES
 In JavaScript, one class can inherit another class
using the extends keyword. The subclass inherits
all the methods ( both static and non-static ) of the
parent class.
 Inheritance enables the reusability and
extensibility of a given class.
 Keyword super can be used to refer to base class
methods/constructors from a subclass.
Example:
class Vehicle {
constructor(make, model) {
/* Base class Vehicle with constructor initializing two-
member attributes */
this.make = make;
this.model = model;
}
}
class Car extends Vehicle {
constructor(make, model, regNo, fuelType) {
super(make, model);
// Sub class calling Base class Constructor
this.regNo = regNo;
this.fuelType = fuelType;
}
getDetails() {

/* Template literals used for displaying details of Car.


*/

console.log(‘${this.make},${this.model},$
{this.regNo},

${this.fuelType}’);

let c = new Car("Hundai", "i10", "KA-016447",


"Petrol"); // Creating a Car object
SUBCLASSING BUILT-INS
 The keywords, class and extends, help developers to create
classes and implement inheritance in the application
where user-defined classes can be created and extended.
Similarly, the built-in classes can be subclassed to add more
functionality.
 To display the array items, the built-in Array class can be
extended as mentioned below.
class MyArray extends Array {
constructor(...args) {
super(...args);
}
display() {
let strItems = "";
for (let val of this) {
strItems += `${val} `;
}
console.log(strItems);
}
 let letters = new MyArray("Sam", "Jack", "Tom");
 letters.display();
 Note that display is not the method present in
Array built-in class. The MyArray subclasses the
Array and adds to it.
 The output of the above code is given below.
 Sam Jack Tom
WORKING WITH EVENTS
 When the interaction happens, the event triggers.
JavaScript event handlers invoke the JavaScript code to
be executed as a reaction to the event triggered.

 When execution of JavaScript code is delayed or


deferred till some event occurs, the execution is
called deferred mode execution. This makes JavaScript
an action-oriented language.
INBUILT EVENTS AND HANDLERS
Event Event-handler Description

When the user clicks on an


click onclick element, the event handler onclick
handles it.

When the user presses the


keypress onkeypress keyboard's key, event
handler onkeypress handles it.

When the user releases the


keyup onkeyup keyboard's key, the event
handler onkeyup handles it.
Event-
Event Description
handler

When HTML document is loaded in


load onload the browser, event handler onload
handles it

When an element loses focus, the


blur onblur
event handler onblur handles it.

When the selection of checked


state change for input, select or
change onchange
text-area element changes, event
handler onchange handles it.
WORKING WITH OBJECTS
 Objects are the real-world entities, used to hold
data that represents the collection of properties is
required.
 An object consists of state and behavior.
 The State of an entity represents properties that
can be modeled as key-value pairs.
 The Behavior of an entity represents the
observable effect of an operation performed on it
and is modeled using functions.
Example:
 A Car is an object in the real world.

 State of Car object:

 Color=red

 Model = VXI

 Current gear = 3

 Current speed = 45 km / hr

 Number of doors = 4

 Seating Capacity = 5

 The behavior of Car object:

 Accelerate

 Change gear

 Brake
TYPE OF OBJECTS
CREATING OBJECTS
 In JavaScript objects, the state and behaviour is
represented as a collection of properties.
 Each property is a [key-value] pair where the key is

a string and the value can be any JavaScript


primitive type value, an object, or even a function.
 JavaScript objects can be created using two

different approaches.
NOTATION
 Object literal notation is a comma-separated list of name-value
pairs wrapped inside curly braces. This promotes the encapsulation
of data in a tidy package.
Syntax:
 objectName = {

//-------------states of the object-----------


key_1: value_1,
key_2: value_2,
...
key_n: value_n,
//-------------behaviour of the object---------
key_function_name_1: function (parameter) {
//we can modify any of the property declared above
},
...
key_function_name_n: function(parameter) {
//we can modify any of the property declared above
}
 }
Example:
//-------------states of the object---------
let myCar = {
name: "Fiat",
model: "VXI",
color: "red",
numberOfGears: 5,
currentGear: 3,
currentSpeed: 45,
//-------------Behaviour of the object---------
accelerate: function (speedCounter) {
this.currentSpeed = this.currentSpeed + speedCounter;
return this.currentSpeed;
},
brake: function (speedCounter) {
this.currentSpeed = this.currentSpeed - speedCounter;
return this.currentSpeed;
}
CREATING OBJECT USING ENHANCED
OBJECT LITERALS
 Below is the older syntax used to create
object literals:
let name = "Arnold";
let age = 65;
let country = "USA";
let obj = { name: name, age: age, country:
country};
 Below is the modern way to create objects in a

simpler way:
let name="Arnold";
let age=65;
let country="USA";
let obj={name,age,country};
CREATING OBJECT USING ENHANCED OBJECT
LITERALS - PROPERTY SHORTHAND
//Literal property without shorthand
function createCourse(name, status) {
return {type: "JavaScript", name: name, status: status};
}
function reviewCourse(name) {
return {type: "JavaScript", name: name};
}
/*Literal property with shorthand when the property and the
value identifiers have the same name, the
identifier can be omitted to make it implicit*/
function createCourse(name, status) {
return {type: "JavaScript", name, status};
}
function reviewCourse(name) {
return {type: "JavaScript", name};
CREATING OBJECT USING ENHANCED
OBJECT LITERALS - COMPUTED PROPERTY

 Earlier in JavaScript to add a dynamic property


to an existing object, below syntax was used.
let personalDetails = {
name: "Stian Kirkeberg",
country: "Norway"
};
let dynamicProperty = "age";
personalDetails[dynamicProperty] = 45;
console.log(personalDetails.age);
//Output: 45
 With newer updates in JavaScript after 2015, the
dynamic properties can be conveniently added using
hash notation and the values are computed to form a
key-value pair.

let dynamicProperty = "age";

let personalDetails = {

name: "Stian Kirkeberg",

country: "Norway",

[dynamicProperty]: 45

};

console.log(personalDetails.age);

//Output: 45
CREATING OBJECT USING FUNCTION CONSTRUCTOR
 To construct multiple objects with the same set of
properties and methods, function constructor can be
used. Function constructor is like regular functions but
it is invoked using a 'new' keyword.
 Example:

 function Car(name, model, color, numberOfGears, curr

entSpeed, currentGear) {
 //-------------States of the object---------

 this.name = name;

 this.model = model;

 this.color = color;

 this.numberOfGears = numberOfGears;

 this.currentSpeed = currentSpeed;

 this.currentGear = currentGear;
//-------------
Behaviour of the object--------- this.accelerate = fun
ction (speedCounter) {
this.currentSpeed = this.currentSpeed + speedCounte
r; return this.currentSpeed;
}
this.brake = function (speedCounter) {
this.currentSpeed = this.currentSpeed - speedCounter
;
return this.currentSpeed;
}
}
 ‘this’ keyword points to an object which owns the

code in the current context.


 It does not have any value of its own but is only the

substitute for the object reference wherever it is


Example:
 To create objects using function constructor, make use of

'new' keyword, and invoke the function. This initializes a


variable of type object. The properties and methods of the
object can be invoked using the dot or bracket operator.
Retrieving state using the dot operator:
 myCar.name; //return "Fiat"

 myCar.currentSpeed; //returns 45

Retrieving behavior using the dot operator:


 myCar.accelerate(50);

//invokes accelerate() with argument = 50


Retrieving state using the bracket operator:
 myCar["name"]; //return "Fiat"

 myCar["currentSpeed"]; //returns 45

Retrieving behavior using the bracket operator:


 myCar["accelerate"](50);

//invokes accelerate() with argument = 50


COMBINING OBJECTS USING SPREAD OPERATOR

 The spread operator is used to combine two or


more objects. The newly created object will hold all the
properties of the merged objects.

Syntax:
 let object1Name = { //properties };
 let object2Name = { //properties };
 let combinedObjectName = {...object1Name, ...object2
Name };

//
the combined object will have all the properties of object
Example:
let candidateSelected={
Name:'Rexha Bebe',
Qualification:'Graduation',
};
let SelectedAs={
jobTitle:'System Engineer',
location:’Bangalore’
};
let employeeInfo={
...candidateSelected,
...SelectedAs
};
console.log(employeeInfo);
/*{ Name: 'Rexha Bebe',
Qualification: 'Graduation',
jobTitle: 'System Engineer',
location: 'Bangalore'} */
CLONING OF OBJECTS USING SPREAD OPERATOR
 It is possible to get a copy of an existing object with
the help of the spread operator.
Syntax:
 let copyToBeMade = { ...originalObject };

 The JSON.stringify() method converts JavaScript


objects into strings.
 When sending data to a web server the data has to

be a string.
Example:
 let originalObj = { one: 1, two: 2, three: 3 };

 let clonedObj = { ...originalObj };


/*Here spreading the object into a list of parameters
happens which return the result as a new object checki
ng whether the objects hold the same contents or not *
alert(JSON.stringify(originalObj) === JSON.stringify(clonedObj));
// true

//checking whether both the objects are equal

alert(originalObj === clonedObj);

// false (not same reference)

//to show that modifying the original object does not

//alter the copy made

originalObj.four = 4;

alert(JSON.stringify(originalObj));

// {"one":1,"two":2,"three":3,"four":4}

alert(JSON.stringify(clonedObj));

// {"one":1,"two":2,"three":3}
DESTRUCTURING OBJECTS
 Destructuring gives a syntax that makes it easy to
create objects based on variables.
 It helps to extract data from an object.

 In the below example an object


is destructured into individual variables:
let myObject = { name: 'Arnold', age: 65, country: 'U
SA' };
let { name, age:currentAge } = myObject;
//alias can be used with :
console.log(name);
console.log(currentAge);
 //OUTPUT: Arnold 65

 An alias currentAge is used for age.


OBJECT DESTRUCTURING IN
FUNCTIONS
let myObject = {
name: 'Marty',
age: 65,
country: 'California'
};
function showDetails({ country }) {
console.log(country);
}
showDetails(myObject);
 //invoke the function using the object

 //OUTPUT: California

 The property 'country' of the object has


been destructured and captured as a function
BROWSER OBJECT MODEL
 As you know that, JavaScript is capable of
dynamically manipulating the content and style
of HTML elements of the web page currently
rendered on the browser.
 This dynamic manipulation of an HTML page on
the client-side itself is achieved with the help of
built-in browser objects.
 They allow JavaScript code to programmatically
control the browser and are collectively known
as Browser Object Model (BOM).
 For programming purposes, the BOM model
virtually splits the browser into different parts and
refers to each part as a different type of built-in
object.
 BOM is a hierarchy of multiple objects.
 'window' object is the root object and consists of
other objects in a hierarchy.
DOCUMENT OBJECT
 The HTML web page that gets loaded on the
browser is represented using the 'document'
object of the BOM model.
 This object considers the web page as a tree which

is referred to as Document Object Model(DOM).


 Each node of this tree represents HTML elements

in the page as 'element' object and its attributes


as properties of the 'element' object.
 W3C provides DOM API consisting of properties

and methods that help in traversal and


manipulation of the HTML page.
 DOM structure that can be accessed using DOM

API methods and properties:


EXAMPLE:
 <html>
 <head>
 <title>JavaScript DOM Implementation</title>
 </head>
 <body>

 <h3>Let us see how HTML is rendered as DOM</

h3> <ul>
 <h5>Here is the list of things we will learn</h5>

 <li>JavaScript Object Document</li>

 </ul>

 </body>

 </html>
DOM STRUCTURE
DOCUMENT OBJECT - METHODS
 To access an element in the HTML page, following
methods can be used on the 'document' object from
DOM.
1. getElementById(x)
 Finds element with id 'x' and returns an object of type

element
 Example:

<p id="p1"> Paragraph 1</p>


<p> Paragraph 2</p>
<script>
//Selects paragraph having id 'p1'
let x=document.getElementById('p1');
x.style.color=“red”;
</script>
//Output: Paragraph 1
DOCUMENT OBJECT - METHODS
2. getElementsByTagName(x)
 Find element(s) whose tag name is 'x' and
return Node List, which is a list of element objects.
 Example:

<p id="p1">Paragraph 1</p>


<p>Paragraph 2</p>
<script>
document.getElementsByTagName('p')
[0].style.color="green";
document.getElementsByTagName('p')
[1].innerHTML="Sample Paragraph2";
</script>
//OUTPUT:
//Paragraph 1
DOCUMENT OBJECT - METHODS
3. getElementsByClassName()
 Find element(s) whose class attribute's values is 'x' and
returns Node List, which is list of element objects.
 Example:
<p class=“p1">Paragraph 1</p> Output:
<p>Paragraph 2</p>
<p class=“p1">Paragraph 1</p>
<script>
//Selects paragraph having class = "myClass"
x=document.getElementsByClassName('p1')[0];
x.style.color="yellow";
</script>
DOCUMENT OBJECT - METHODS
4. querySelectorAll()
 Find element(s) by CSS selectors and return Node
List, which is a list of element objects.
 Example:
<p class="p1"> Paragraph 1</p>
<p> Paragraph 2</p>
<p id="p1"> Paragraph 3</p>
<p class="p1">Paragraph 1</p>
<script>
var x = document.querySelectorAll("p#p1");
x[0].innerHTML="selected element text";
</script>
<p class="p1"> Paragraph <p class="p1"> Paragraph
1</p> 1</p>
<p> Paragraph 2</p> <p> Paragraph 2</p>
<p id="p1"> Paragraph 3</p> <p id="p1"> Paragraph 3</p>
<p class="p1">Paragraph1</p> <p
<script> class="p1">Paragraph1</p>
var x = <script>
document.querySelectorAll( var x =
"p#p1"); document.querySelectorAll("
p.p1");
x[0].innerHTML="selected
element text"; x[0].innerHTML="selected
element text";
</script>
</script>
DOCUMENT OBJECT - PROPERTIES

 Some of the other properties of the 'document'


object to access the HTML element are:
 the body returns body element.

Usage: document.body;
 the forms return all form elements.

Usage: document.forms;
 the head returns the head element.

Usage: document.head;
 the images return all image elements.

Usage: document.images;
 To manipulate the content of HTML page, the following
properties of 'element' object given by DOM API can be
used:
 innerHTML

 It gives access to the content within HTML elements like

div, p, h1, etc. You can set/get a text.


 Example:

<div id="div1">
<h1 id="heading1">Welcome to JavaScript Tutorial</h1>

<p id="para1" style="color: blue;">Let us learn DOM API</


p>
</div>
<script> //retieves current content
document.getElementById("heading1").innerHTML;
//sets new content
document.getElementById("heading1").innerHTML =
"Heading generated dynamically" </script>
 Attribute: to set new values to given attributes.
<style>
.democlass {
color: red;
}
</style>
<body>
<h1 id="myH1">The Element Object</h1>
<h2>The setAttribute() Method</h2>
<p>Click "Add Class" to add a class attribute to the h1
element:</p>
<button onclick="myFunction()">Add Class</button>
<script>
function myFunction() {
document.getElementById("myH1").setAttribute("class",
"democlass");
}
 Output:
 Initially, no color was applied to the heading, later the
class ‘democlass’ was added using setAttribute.

Style:
 It gives access to the style attribute of the HTML
element and allows it to manipulate the CSS
modifications dynamically.
 Example:

<div id="div1">

<h1 id="heading1">Welcome to JavaScript Tutorial</


h1>

<p id="para1" style="color: blue;">Let us learn DOM AP


I</p>

</div>

<script>

//resets style property

document.getElementById("div1").style.color = "red";
WINDOW OBJECT
 So far, you know how the content and style for a
given HTML page can be modified using the
Browser Object model's object 'document'.
 Suppose it is not required to update the HTML page

but only certain properties of the browser window


on which it is rendered.
 That is to navigate to a different URL and display a

new web page, or close the web page or store


some data related to the web page. Well, to
implement this, an object that represents the
entire browser window and allows us to access and
manipulate the window properties is required.
 Window object resides on top of the BOM

hierarchy. Its methods give us access to the


toolbars, status bars, menus, and even the HTML
web page currently displayed.
WINDOW OBJECT - PROPERTIES

1. innerHeight
 This property holds the inner height of the
window’s content area.
 Example:
 let inHeight = window.innerHeight;
 console.log(" Inner height: " + inHeight);
 //Returns Inner height: 402
WINDOW OBJECT - PROPERTIES
2. innerWidth
 This property holds the inner width of the window’s

content area.
 Example:

let inWidth = window.innerWidth;


console.log(" Inner width: " + inWidth);
//Returns Inner width: 1366
3. outerHeight
 This property holds the outer height of the window

including toolbars and scrollbars.


 Example:

let outHeight = window.outerHeight;


console.log(" Outer Height: " + outHeight);
//Returns Outer height: 728
WINDOW OBJECT - PROPERTIES

4. outerWidth
 This property holds the outer width of the
window including toolbars and scrollbars.
 Example:

let outWidth = window.outerWidth;

console.log("Outer width of window: " + outWidt


h);

//Returns Outer width: 1366


WINDOW OBJECT - METHODS
1. localStorage
 This property allows access to objects that stores data

without any expiration date.


 Example:

localStorage.setItem('username','Bob');
console.log("Item stored in localStorage is" +
localStorage.getItem('username'));
//Returns Item stored in localStorage is Bob
2. sessionStorage
 This property allows access to objects that stores data

valid only for the current session.


 Example:

sessionStorage.setItem('password', 'Bob@123');
console.log("Item stored in sessionStorage is " +
sessionStorage.getItem('password'));
//Returns Item stored in sessionStorage is Bob@123
 Methods
 In addition to these methods, 'window' object
gives us a few more methods that are helpful in
the following way:
 open() method, opens a new window.
Usage: window.open("http://www.xyz.com");
 close() method, closes the current window.
Usage: window.close();
HISTORY OBJECT
 If the concern is about the list of URLs that have
been visited by the user and there is no need for
any other information about the browser, BOM
gives the 'history' object for this.
Property:
 length returns the number of elements in the

History list. Usage: history.length;


Methods:
 back() method, loads previous URL from history

list. Usage: history.back();


 forward() method, loads next URL from
history list. Usage: history.forward();
 go() method, loads previous URL present at the

given number from the history list


NAVIGATION OBJECT
 It contains information about the client, that is,
the browser on which the web page is rendered.
1. appName
 Returns the name of the client.

Example:
 navigator.appName; //Browser's name: Netscape

2. appVersion
 Returns platform (operating system) and version

of the client (browser).


Example:
 console.log(navigator.appVersion);

 //5.0 (Windows NT 10.0; Win64; x64)

 //AppleWebKit/537.36 (KHTML, like Gecko)

 //Chrome/83.0.4103.106 Safari/537.36
3. Platform
 Returns the name of the user's operating system.

Example:
 console.log(navigator.platform);

 //Browser's platform: Win 32

4. userAgent
 Returns string equivalent to HTTP user-agent request

header.
 Example:

 console.log(navigator.userAgent);

 //Browser's useragent: Mozilla/

5.0 5.0 (Windows NT 6.1; WOW64)


 //AppleWebKit/537.36 (KHTML, like Gecko) //Chrome/

53.0.2785.116 Safari/537.36
 The output shown above is for the Chrome browser

running on Windows.
LOCATION OBJECT
 'location' object, contains information about the current
URL in the browser window. The information can be
accessed or manipulated using the following properties
and methods.
 If this is the URL:
http://localhost:8080/JS_Demos/myLocationFile.html,
 properties have the following interpretation:

1. href
 It contains the entire URL as a string.

Example:
 console.log(location.href); //Returns http://
2. hostname
 It contains the hostname part of the URL.

Example:
 console.log(location.hostname); //Returns localhost

3. port
 It contains a port number associated with the URL.

Example:
 console.log(location.port) //Returns 8080

4. pathname
 It contains a filename or path specified by the object.

Example:
 console.log(location.pathname);
 //Returns /JS_Demos/myLocationFile.html
 'location' object gives the following methods to reload the
current page or to navigate to a new page:

1. assign()
 Loads new HTML document.

Example:
 location.assign('http://www.facebook.com');
 //Opens facebook page

2. reload()
 Reloads current HTML.

Example:
 location.reload();
 //Current document is reloaded
DOCUMENT OBJECT MODEL
 DOM Nodes:
 BOM hierarchy consisting of numerous built-in objects
allows to dynamically manipulate the given web page on
the client-side.
 There is one more kind of manipulation that can be
achieved on the DOM tree. HTML elements can be
dynamically added or removed.
 According to the W3C DOM standard, each HTML element
can be referred to as a Node. For example, the entire
HTML document is a 'document node', every other element
inside HTML is 'element node'. The content inside these
HTML elements is a 'text node'.
EXAMPLE:
<html>
<head>
<title>JavaScript DOM Implementation</title>
</head>
<body>

<h3>Let us see how HTML is rendered as DOM</h


3> <ul>
<h5>Here is the list of things we will learn</h5
> <li>JavaScript Object Document</li>
</ul>
</body>
</html>
DOM STRUCTURE
 So, how does the Node relationship helps in Node
manipulation?
 These nodes appear in a hierarchical structure inside
the browser.
 And this hierarchical relationship between the nodes
allows us to traverse through the DOM tree.
 The top node is called the root. It does not have any
parents.
 Every other node in the tree belongs to one parent.
 Every node may have several children.
 Nodes with the same parent are referred to as siblings.
DOM API PROPERTIES
1. parentNode
 Returns a Node object that is the parent node of the specified

node. This property can be retrieved and cannot set it.


Example:
<body>
<ul id="u1">
<li id="l1">B.Tech</li>
<li>M.Tech</li>
</ul>
<p id="p1"></p>
<script>
//Returns Node object<html>
let x=document.getElementById('l1').parentNode.nodeName;

document.write(x);
document.getElementById('p1').innerHTML=x;
</script>
</body>
DOM API PROPERTIES
2. childNodes
 Returns NodeList object, i.e collection of child nodes

of the specified node. Each child can be accessed


by an index number that refers to its position inside
the parent element. The first position is at index
'0'.
Example:
<script>
let x=document.getElementById('u1').childNodes;

let text="";
for(let i=0;i<x.length;i++){
text+=x[i].nodeName+"<br>";
}
document.getElementById('p1').innerHTML=text;
DOM API PROPERTIES
3. firstChild
 Returns Node object which is the first child of the

specified node. Its is equivalent to childNodes[0].


Example:
<body>
<ul id="u1"><li id='l1'>B.Tech</li><li>M.Tech</li>
</ul>
<p id="p1"></p>
<script>
let
x=document.getElementById('u1').firstChild.innerHTML;

document.getElementById('p1').innerHTML=x;
</script>
</body>
 Note: Whitespace inside elements is considered as
DOM API PROPERTIES
4. lastChild
 Returns Node object which is the last child of the

specified node.
Example:
<body>
<ul id="u1"><li
id='l1'>B.Tech</li><li>M.Tech</li></ul>
<p id="p1"></p>
<script>
Let x=document.getElementById('u1').lastChild.innerHTML;

document.getElementById('p1').innerHTML=x;
</script>
</body>
DOM API PROPERTIES
5. nextSibling returns the Node object of the node that
immediately follows the specified node at the same tree
level.
Example:
<body>
<ul id="u1"><li
id='l1'>B.Tech</li><li>M.Tech</li></ul>
<h1>course</h1>
<p id="p1"></p>
<script>
let x=document.getElementById('l1').nextSibling.innerHTML;

document.getElementById('p1').innerHTML=x;
</script>
</body>
DOM API PROPERTIES
6. previousSibling
 Returns the Node object of the node that the

previous node of the specified node at the same


tree level.
Example:
 <body> <ul id="u1"><li>M.Tech</li><li

id='l1'>B.Tech</li></ul><h1
id="h1">course</h1><p id="p1"></p>
 <script>

 let

x=document.getElementById('h1').previousSibling.
innerHTML;
 document.getElementById('p1').innerHTML=x;

 </script>


Please note:
 Similar to all these properties of Node object, you
also have properties such as parentElement,
firstElementChild, lastElementChild,
nextElementSibling and previousElementSibling.
 The difference is that element properties return
only the Element object whereas node properties
return element, text, and attribute nodes with
respect to the specified node. Also, whitespaces are
considered as '#text' nodes by the node
properties.
NODE MANIPULATION
 The node relationship allows to modify the tree of
nodes by adding new nodes and removing the
existing nodes if required.
 For the given HTML page, below methods will do
the following:
 Create a new element
 Create new content
 Add new content to the new element
 Add a new element to the existing DOM tree
NODE MANIPULATION
HTML code:

<div id="div1">

<h1 id="heading1">Hello World</h1>


<p id="para1">Good luck!!</p>

</div>

<br>

<input type="button" value="Add span"


onclick="createNew()">

<input type="button" value="Remove para"


onclick="removeOld()">
NODE MANIPULATION METHODS
1. createElement()
 Creates a new element.

Example:
 let newElement = document.createElement('span');

2. createTextNode()
 Creates content at runtime. This node then can
be appended to any node that can hold content.

Example:
 let newTextElement = document.createTextNode('The s
pan is added just now');
3. appendChild()
 Appends a newly created element to the existing DOM tree
at the desired position.

Example:

newElement.appendChild(newTextElement);

document.getElementById('div1').appendChild(newElement);

4. removeChild()
 Removes the element from the existing DOM tree.

Example:

document.getElementById('div1').removeChild(document.get
ElementById('para1'));
ARRAYS
 Objects in JavaScript is a collection of properties stored
as key-value pair.
 Often, there is requirement for an ordered collection,
where there are 1st, 2nd, 3rd element, and so on. For
example, you need to store a list of students in a class
based on their roll numbers.
 It is not convenient to use an object here, because
objects don’t store the values in an ordered fashion.
Also, a new property or element cannot be inserted
"between" the existing ones.
 This is why Array is used to store values in order.
 Array in JavaScript is an object that allows storing multiple
values in a single variable. An array can store values of
any datatype.
 An array's length can change at any time, and data can be
stored at non-contiguous locations in the array,
Example:
 let numArr = [1, 2, 3, 4];
 let empArr = ["Johnson", 105678, "Chicago"];
 The elements of the array are accessed using an index
position that starts from 0 and ends with the value equal
to the length of the array minus 1.
Example:
 let numArr = [1, 2, 3, 4];
 console.log(numArr[0]); //1
 console.log(numArr[3]); //4
CREATING ARRAYS
 Arrays can be created using the literal notation or
array constructor.

Array Literal Notation:


 Arrays are created using literal notation almost all
the time.

Syntax:
 let myArray = [element 1, element2,…, element N];

Example:
 let colors = ["Red", "Orange", "Green"]
ARRAY CONSTRUCTOR
 Arrays can be created using the Array constructor
with a single parameter which denotes the array
length.
 This creates empty slots for the array elements. If
the argument is any other number, a RangeError
exception is thrown.

Syntax:
 let myArray = new Array(arrayLength);
ARRAY CONSTRUCTOR
Example:
let colors = new Array(2);
console.log(colors.length); //2
//Assign values to an empty array using indexes
colors[0] = "Red";
colors[1] = "Green";
console.log(colors); //['Red','Green']

 If more than one argument is passed to the Array


constructor, a new Array with the given elements is
created.
 Syntax:

let myArray = new Array(element 1, element 2,…,element


N);
 Example:

let colors = new Array("Red", "Orange", "Green");


DESTRUCTURING ARRAYS
 To unpack values from arrays or objects into distinct
variables.
Example:
// we have an array with the employee name and id
let empArr = ["Shaan", 104567];
// destructuring assignment
// sets empName = empArr[0]
// and empId = empArr[1]
let [empName, empId] = empArr;
console.log(empName); // Shaan
console.log(empId); // 104567
 Destructuring assignment syntax is just a shorter way to

write:
let empName = empArr[0];
let empId = empArr[1];
 You can also ignore elements of the array using an extra
comma.
Example:
let [empName, , location] = ["Shaan", 104567, "Bangalore"];
//
Here second element of array is skipped and third element is
assigned to location variable
console.log(empName); // Shaan
console.log(location); // Bangalore
 Rest operator can also be used with destructuring assignment

syntax.
Example:
let [empName, ...rest] = ["Shaan", 104567, "Bangalore"];
console.log(empName); // Shaan
console.log(rest); // [104567,'Bangalore']
 Here, the value of the rest variable is the array of remaining

elements and the rest parameter always goes last in the


destructuring assignment.
ACCESSING ARRAYS
 Array elements can be accessed using indexes. The first
element of an array is at index 0 and the last element is at
the index equal to the number of array elements – 1.
 Using an invalid index value returns undefined.

Example:
 let arr = ["first", "second", "third"];

 console.log(arr[0]); //first

 console.log(arr[1]); //second

 console.log(arr[3]); //undefined

Loop over an array


 You can loop over the array elements using indexes.

 Example:

 let colors = ["Red", "Orange", "Green"];

 for (let i = 0; i < colors.length; i++) {

 console.log(colors[i]);


 JavaScript also provides for..of statement to
iterate over an array.

Example:
 let colors = ["Red", "Orange", "Green"];
 // iterates over array elements

for (let color of colors)

console.log(color);

} //Red//Orange//Green
ARRAY METHODS
Array Property:
 JavaScript arrays consist of several useful methods

and properties to modify or access the user-defined


array declaration.
 Below is the table with property of JavaScript array:

Property Description Example

let myArray = ["Windows"


It is a read-only property. , "iOS", "Android"];
It returns the length of
length console.log("Length = " +
an array, i.e., number of
myArray.length);
elements in an array
//Length = 3
ARRAY METHODS TO ADD/REMOVE ARRAY ELEMENTS
Method
Description Example
s
let myArray=["Android", "iOS",
"Windows"];
Adds new element to
the end of an array myArray.push("Linux"); //4
push()
and return the new console.log(myArray);
length of the array.
//["Android","iOS","Windows",
"Linux"]
let myArray = ["Android", "iOS
", "Windows"];
Removes the last
console.log(myArray.pop());
element of an array
pop()
and returns that // Windows
element. console.log(myArray);
// ["Android","iOS"]
Methods Description Example

let myArray = ["Android", "i


OS", "Windows"];
Removes the first
console.log(myArray.shift())
shift() element of an array and
; //Android
returns that element.
console.log(myArray);
//["iOS", "Windows"]

let myArray = ["Android", "i


OS", "Windows"];
Adds new element to
the beginning of an myArray.unshift("Linux");
unshift()
array and returns the console.log(myArray);
new length
//["Linux","Android","iOS",
"Windows"]
Methods Description Example

Change the content of an


array by inserting, removing,
and replacing elements.
Returns the array of removed let myArray = ["Androi
elements. d", "iOS", "Windows"];
Syntax: //inserts at index 1
array.splice(index, myArray.splice(1, 0,
splice() deleteCount, items); "Linux");
index = index for new item console.log(myArray);
deleteCount = number of // ["Android","Linux",
items to be removed, starting
"iOS", "Windows"]
from index next to index of
new item
items = items to be added
Methods Description Example
let myArray1 = ["Android","iOS"];
let myArray2 = ["Samsung",
Joins two or more "Apple"];
concat() arrays and returns console.log(myArray1.concat( m
joined array. yArray2));
//["Android", "iOS", "Samsung",
"Apple"]

Returns a new array Syntax:


object copying to it all
array.slice(start,end)
items from start to
end(exclusive) where let myArray=["Android","iOS",
slice()
start and end represents "Windows"];
the index of items in an
console.log(myArray.slice(1,3));
array. The original array
remains unaffected // ["iOS", "Windows"]
METHODS TO SEARCH AMONG ARRAY ELEMENTS

Methods Description Example

let myArray = ["Android","iO


S", "Windows","Linux"];
Returns the index for the console.log(myArray.indexOf(
first occurrence of an "iOS")); // 1
indexOf()
element in an array and -1 if
it is not present console.log(myArray.indexOf(
"Samsung"));
//-1
Method
Description Example
s
Returns the value of the first element
in an array that passes a condition
specified in the callback function.
Else, returns undefined if no element
passed the test condition.
let myArray = ["Androi
Syntax:
d", "iOS", "Windows", "
array.find(callback(item,index,array)) Linux"];
callback is a function to execute on let result = myArray.fin
find()
each element of the array d(element => element.
length > 5);
item value represents the current
element in the array console.log(result); //
Android
index value indicates index of the
current element of the array
array value represents array on
which find() is used,
index and array are optional
Methods Description Example
•Returns the index of the first
element in an array that passes a
condition specified in the callback
function. Returns -1 if no element
passes the condition.
•Syntax: let myArray = ["Androi
d", "iOS", "Windows",
•Array.findIndex(callback(item,inde
"Linux"];
x,array));
let result =
findIndex() •callback is a function to execute
on each element of the array myArray.findIndex(ele
ment => element.leng
•item value represents current
th > 5);
element in the array
console.log(result) //0
•index represents index of the
current element of the array
•array represents array on which
findIndex() is used.
•index and array are optional
Methods Description Example
Creates a new array with
elements that passes the test
provided as a function. let myArray=["Androi
d", "iOS", "Windows",
Syntax:
"Linux"];
array.filter(callback(item,index,
let result =
array))
myArray.filter(elemen
callback is the Function to test
filter() t => element.length
each element of an array
> 5);
item value represents the
console.log(result)
current element of the array
//
index value represents Index of
["Android","Windows"
current element of the array
]
array value indicates array on
which filter() is used.
METHODS TO ITERATE OVER ARRAY
ELEMENTS
Method Description Example
Iterates over an array to access
each indexed element inside an
array. let myArray = ["Android
", "iOS", "Windows"];
Syntax:
myArray.forEach((eleme
array,forEach(callback(item,inde
nt, index) =>
x, array))
console.log(index + "-"
callback is a function to be
+
forEach() executed on each element of an
array element));

item value represents current //0-Android


element of an array //1-iOS
index value mentions index of //2-Windows
current element of the array
//3-Linux
array represents the array on
which forEach() is called
METHODS TO TRANSFORM AN ARRAY
Method
Description Example
s
Creates a new array from the
results of the calling function
for every element in the array.
Syntax:
let numArr = [2, 4,
array.map(callback(item,index, 6, 8];
array))
let result = numArr.
callback is a function to be run
map() map(num=>num/
for each element in the array
2);
item represents the current
console.log(result);
element of the array
//[ 1, 2, 3, 4 ]
index value represents index of
the current element of the array
array value represents array on
Methods Description Example
let myArray = ["Android"
, "iOS", "Windows"];
Returns a new string console.log(myArray.join(
by concatenating all ));
the elements of the
// Android,iOS,Windows
array, separated by a
join()
specified operator console.log(
such as comma. myArray.join('-'));
Default separator is
comma // Android-iOS-Windows
INTRODUCTION TO
ASYNCHRONOUS PROGRAMMING
Consider below-given code snippet:
console.log("Before For loop execution");
for (var i = 0; i < 2; i++) {
console.log("setTimeout message");
func1();
func2();
}
console.log("After For loop execution");
function func1() {
console.log("Am in func1");
}
function func2() {
console.log("Am in func2");
 According to JavaScript sequentially execution
nature, the output of the above code snippet
would be as shown below:
 If previous code is modified by adding
setTimeout() method in for loop as shown below,
then observe the output once again.
 Modified code snippet:

 for (var i = 0; i < 2; i++) {

 setTimeout(function() {

console.log("setTimeout message");
func1();
 },

 );

 func2();

}

 The setTimeout() method calls a function after a

number of milliseconds and is executed only


once.
NEW OUTPUT

• As observed in the output above, due to usage of


setTimeout() method, the entire execution of code
behavior has been changed, and the code has been
executed asynchronously.
ASYNCHRONOUS PROGRAMMING

 Asynchronous execution refers to a


programming technique where multiple tasks
can be executed concurrently, without
blocking the execution of the main thread.
 In this approach, a task can start executing
without waiting for the completion of another
task.
ASYNCHRONOUS PROGRAMMING
TECHNIQUES
 Some of the real-time situations where you may
need to use the JavaScript Asynchronous code of
execution while implementing business logic are:
 To make an HTTP request call.

 To perform any input/output operations.

 To deal with client and server communication.

These executions in JavaScript can also be achieved


through many techniques.
 Some of the techniques are:

 Callbacks

 Promises

 Async/Await
CALLBACKS
 A callback function is a function that is passed as an

argument to another function.

 Callbacks make sure that a certain function does

not execute until another function has already finished

execution.

 Here the problem is there are bunch of asynchronous

tasks, which expect you to define one callback within

another callback and so on. This leads to callback hell.


 Callback hell, which is also called a Pyramid of Doom, consists of
more than one nested callback which makes code hard to read
and debug. As calls become more nested, the code becomes
deeper and increasingly more difficult to manage, especially if
there are more loops, conditional statements, and so on in the
code.
 Example:
 myFun1(function () {
myFun2(function () {
myFun3(function () {
myFun4(function () {
....
});
});
});
 });
 In the above example, it is noticed that the "pyramid" of nested
calls grows to the right with every asynchronous action. It leads to
callback hell. So, this way of coding is not very good practice.
 To overcome the disadvantage of callbacks, the concept of
PROMISES
 In JavaScript, promises are a way to handle
asynchronous operations.
 A promise is an object that represents a value that
may not be available yet, but will be resolved at
some point in the future.
 Promises are commonly used for network requests,
file I/O, and other time-consuming operations.
 Promises have three states:
 Pending: The initial state, before the promise has
resolved or rejected.
 Fulfilled: The state when the promise has
successfully resolved with a value.
 Rejected: The state when the promise has failed
to resolve with an error.
 Promises can be created using the Promise
constructor, which takes a function as its argument.
 This function takes two parameters: resolve and

reject. The resolve function is used to fulfill the


promise, and the reject function is used to reject the
promise with an error.
Example:
 const promise = new Promise((resolve, reject) => {

 // Perform some asynchronous operation

 // When it's done, call either `resolve` or `reject`

 if (/* operation was successful */) {

 resolve('result');
 } else {

 reject(new Error('Something went wrong'));


 }

 });
 Once a promise is created, you can attach callbacks
using the then and catch methods. The then method
is called when the promise is fulfilled, and the catch
method is called when the promise is rejected.

Example:

promise.then((result) => {

console.log(result); // output: 'result'

}).catch((error) => {

console.error(error); // output: 'Error: Something


went wrong'

});
Example:
 function fetchData() {

 return new Promise((resolve, reject) =>

{ setTimeout(() => {
 resolve("Data fetched successfully!");

 }, 2000);

 });

}

 fetchData()

 .then((data) => {

 console.log(data);

 })

 .catch((error) => {

 console.error(error);

 });
 Promises can also be chained using the then method.
This allows you to perform a series of asynchronous
operations in a specific order.

Example:
 promise.then((result) => {
 return doSomethingElse(result);
 }).then((result) => {
 console.log(result); // output: 'result from second
operation'
 }).catch((error) => {
 console.error(error);
 });
// Nested callbacks using setTimeout

 setTimeout(function() {
 console.log('First timeout executed');
 setTimeout(function() {
 console.log('Second timeout
executed');
 setTimeout(function() {
 console.log('Third timeout
executed');
 }, 1000);
 }, 1000);
 }, 1000);
function wait(ms) {
return new Promise(function(resolve) {
setTimeout(resolve, ms);
});
}

wait(1000)
.then(function() {
console.log('First timeout executed');
return wait(1000);
})
.then(function() {
console.log('Second timeout executed');
return wait(1000);
})
.then(function() {
console.log('Third timeout executed');
});
 In the above examples, the first code block uses nested
callbacks to execute three timeouts with a delay of one
second between them.
 The second code block uses the wait() function to create
a promise that resolves after a specified delay, and then
chains three promises together to execute the three
timeouts with a delay of one second between them.
 The then() method is used to chain the promises
together.
 By using promises, the code is more readable and easier
to maintain, and it avoids the pitfalls of callback hell.
ASYNC/AWAIT
 With async/await, you can write asynchronous code in
a way that looks and feels like synchronous code,
making it easier to read and debug.
 By marking a function with the async keyword, you are
indicating that it contains asynchronous code.
 Within an async function, you can use the await
keyword to pause the execution of the function until a
Promise is resolved or rejected.
 This allows you to write asynchronous code in a more
linear, step-by-step fashion, without the need for
nested callbacks or complex Promise chains.
ASYNC/AWAIT
 "async/await" is simple, easy, readable and
understandable than the promises.
 Async/Await vs Promises

Async/Await Promises
Only the promise
The entire wrapper
Scope chain itself is
function is asynchronous.
asynchronous.
 Synchronous work
 Synchronous work
needs to be moved out
can be handled in
of the callback.
Logic the same callback.
 Multiple promises can
 Multiple promises
be handled with simple
use Promise.all().
variables.

You can use try, catch and You can use then,
Error Handling
finally. catch and finally.
USING ASYNC/AWAIT
 Async Function
 An async function is declared with an async keyword. It
always returns a promise and if the value returned is not a
promise, the JavaScript will automatically wrap the value in
a resolved promise.
 Example:
 async function hello() {
//Value will be wrapped in a resolved promise and returned
 return "Hello Async";

 }

 hello().then(val =>console.log(val)); // Hello Async

 async function hello() {

//Promise can be returned explicitly as well


 return Promise.resolve("Hello Async");

 }

 hello().then(val => console.log(val)); // Hello Async


 Await
 Await keyword makes JavaScript wait until the
promise returns a result. It works only inside async
functions.
 JavaScript throws Syntax error if await is used
inside regular functions.
 Await keyword pauses only the async function
execution and resumes when the Promise is
settled.
 Example:
 function sayAfter2Seconds(x) {

 return new Promise(resolve => {

setTimeout(() => {
resolve(x);
}, 2000);
});
}
async function hello() {
//wait until the promise returns a value
var x = await
sayAfter2Seconds("Hello Async/Await");
console.log(x); //Hello Async/Await
}
hello();
EXECUTING NETWORK REQUESTS
USING FETCH API
 Fetch API:
 JavaScript plays an important role in
communication with the server. This can be
achieved by sending a request to the server and
obtaining the information sent by the server.
 For example:

 Submit an order,

 Load user information,

 Receive latest information updates from the server

 All the above works without reloading the current

page!
 There are many ways to send a request and get a
response from the server. The fetch() is a modern
and versatile method available in JavaScript.
 Fetch provides a generic definition
of Request and Response objects.
 The fetch() method takes one mandatory
argument, the path to the resource you want to
fetch.
 It returns a Promise that resolves to Response if

the fetch operation is successful or throws an error


that can be caught in case the fetch fails. You can
also optionally pass in an init options object as the
second argument.
 Syntax:

 PromiseReturned = fetch(urlOfTheSite, [options])


 urlOfTheSite – The URL to be accessed.
 options – optional parameters: method, headers,
etc.
 Without options, this is a simple/default GET
request which downloads the contents from
the URL. The fetch() returns a promise which
needs to be resolved to obtain the response from
the server or for handling the error.
FETCH() METHOD
 Getting a response from a fetch() is a two-step process.
 1. The promise object returned by fetch() needs to be

resolved to an object after the server sends a response.


 Here, HTTP status needs to be checked to see it is

successful or not.
 The promise will be rejected if the fetch is unable to

make a successful HTTP-request to the server e.g. may


be due to network issues, or if the URL mentioned in
fetch does not exist.
 HTTP-status can be seen in response properties easily

by doing console.log
 status – HTTP status code returned from a response,
e.g., 200.
 ok – Boolean, true if the HTTP status code returned

from a response, is 200-299.


 2. Get the response body using additional methods.
 Response object can be converted into various formats by using
multiple methods to access the body/data from response object:
 response.text() –read body/data from response object as a text.
 response.json() – parse body/data from response object as JSON.
 response.formData() – return body/data from response object
as FormData.
 response.blob() – return body/data from response object
as Blob (binary data with its type).
 //pass any url that you wish to access to fetch()
 let response = await fetch(url);
 if (response.ok) { // if HTTP-status is 200-299
 // get the response body
 let json = await response.json();
 console.log(json);
 }
 else {
 console.log("HTTP-Error: " + response.status);
 }
MODULAR PROGRAMMING
 Modules are one of the most important features of
any programming language.
 In 2015 modules were introduced in JavaScript
officially and they are considered to be first-class
citizens while coding the application.
 We need modules in order to effectively reuse,
maintain, separate, and encapsulate internal
behavior from external behavior.
 Modules are always by default in strict-mode code.
That is the scope of the members (functions, variables,
etc.) which reside inside a module is always local.
 The functions or variables defined in a module are not
visible outside unless they are explicitly exported.
 The developer can create a module and export only
those values which are required to be accessed by
other parts of the application.
 The keyword "export" is used to export any
variable/method/object from a module.
 The keyword "import" is used to consume the exported
variables in a different module.
CREATING MODULES
 The export keyword is used to export some
selected entities such as functions, objects,
classes, or primitive values from the module so
that they can be used by other modules using
import statements.
 There are two types of exports:
 Named Exports (More exports per
module)
 Default Exports (One export per module)
NAMED EXPORTS
 Named exports are recognized by their names. You can
include any number of named exports in a module.
 There are two ways to export entities from a module.
 1. Export individual features
 Syntax:
 export let name1, name2, …, nameN; // also var, const
 export let name1 = …, name2 = …, …, nameN;
 export function functionName(){...}
 export class ClassName {...}
 Example:
 export let var1,var2;
 export function myFunction() { ... };
 2. Export List
 Syntax:
 export { name1, name2, …, nameN };
 Example:
 export { myFunction, var1, var2 };
DEFAULT EXPORTS
 The most common and highly used entity is
exported as default. You can use only one default
export in a single file.
 Syntax:

 export default entityname;

 where entities may be any of the JavaScript

entities like classes, functions, variables, etc.


 Example:

 export default function () { ... }

 export default class { .. }

 You may have both default and named exports in

a single module.
CONSUMING MODULES
 How to import Named Exports:
 If you want to utilize an exported member of a

module, use the import keyword. You can use


many numbers of import statements.
 Syntax:

 //import multiple exports from module

 import {entity1, entity 2... entity N} from


modulename;
 //import an entire module's contents

 import * as variablename from modulename;

 //import an export with more convenient alias

 import {oldentityname as newentityname } from

modulename;
 Example:
 import {var1,var2} from './mymodule.js';
 import * as myModule from './mymodule.js';
 import {myFunction as func} from
'./mymodule.js';
HOW TO IMPORT DEFAULT
EXPORTS

 You can import a default export with any


name.
 Syntax:
 import variablename from modulename;
 Example:
 import myDefault from './mymodule.js';
Thank You

You might also like