Java Script Part 2 PPT-Unit2 MSD
Java Script Part 2 PPT-Unit2 MSD
(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
2. Built-in functions
//statements to be executed
}
Example:
}
The code written inside the function body will be
executed only when it is invoked or called.
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
console.log("Welcome to JavaScript");
};
sayHello();
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.
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.
console.log(trip());
// Let's go to trip.
Syntax 3: One parameter, single line code:
If only one parameter, then () is not required.
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.
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
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.
console.log(multiply(10)); //10
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:
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:
// Mark India
showDetails(myObject);
The properties name and country of the object have
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(){
function message() {
message();
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
console.log(‘${this.make},${this.model},$
{this.regNo},
${this.fuelType}’);
Color=red
Model = VXI
Current gear = 3
Current speed = 45 km / hr
Number of doors = 4
Seating Capacity = 5
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
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 = {
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
let personalDetails = {
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:
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
myCar.currentSpeed; //returns 45
myCar["currentSpeed"]; //returns 45
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 };
be a string.
Example:
let originalObj = { one: 1, two: 2, three: 3 };
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.
//OUTPUT: California
h3> <ul>
<h5>Here is the list of things we will learn</h5>
</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:
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
<div id="div1">
<h1 id="heading1">Welcome to JavaScript Tutorial</h1>
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">
</div>
<script>
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
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:
4. outerWidth
This property holds the outer width of the
window including toolbars and scrollbars.
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
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
Example:
navigator.appName; //Browser's name: Netscape
2. appVersion
Returns platform (operating system) and version
//Chrome/83.0.4103.106 Safari/537.36
3. Platform
Returns the name of the user's operating system.
Example:
console.log(navigator.platform);
4. userAgent
Returns string equivalent to HTTP user-agent request
header.
Example:
console.log(navigator.userAgent);
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>
document.write(x);
document.getElementById('p1').innerHTML=x;
</script>
</body>
DOM API PROPERTIES
2. childNodes
Returns NodeList object, i.e collection of child nodes
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
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
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">
</div>
<br>
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.
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']
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
Example:
let arr = ["first", "second", "third"];
console.log(arr[0]); //first
console.log(arr[1]); //second
console.log(arr[3]); //undefined
Example:
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
console.log(color);
} //Red//Orange//Green
ARRAY METHODS
Array Property:
JavaScript arrays consist of several useful methods
setTimeout(function() {
console.log("setTimeout message");
func1();
},
);
func2();
}
Callbacks
Promises
Async/Await
CALLBACKS
A callback function is a function that is passed as an
execution.
resolve('result');
} else {
});
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) => {
}).catch((error) => {
});
Example:
function fetchData() {
{ 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";
}
}
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,
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
successful or not.
The promise will be rejected if the fetch is unable to
by doing console.log
status – HTTP status code returned from a response,
e.g., 200.
ok – Boolean, true if the HTTP status code returned
a single module.
CONSUMING MODULES
How to import Named Exports:
If you want to utilize an exported member of a
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