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

Javascript Notes

The document provides an overview of key JavaScript concepts: 1. JavaScript can make webpages interactive through features like form validation and animation. Variables store data and are case-sensitive. 2. JavaScript supports both implicit and explicit type conversions between data types. Common conversion methods include Number(), parseInt(), and parseFloat(). 3. Loops repeat code blocks and break and continue statements control loop execution. Functions make code reusable. Scope determines where variables are accessible.

Uploaded by

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

Javascript Notes

The document provides an overview of key JavaScript concepts: 1. JavaScript can make webpages interactive through features like form validation and animation. Variables store data and are case-sensitive. 2. JavaScript supports both implicit and explicit type conversions between data types. Common conversion methods include Number(), parseInt(), and parseFloat(). 3. Loops repeat code blocks and break and continue statements control loop execution. Functions make code reusable. Scope determines where variables are accessible.

Uploaded by

Vinita Deshpande
Copyright
© © All Rights Reserved
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 40

Javascript Notes

 JavaScript used mainly for making webpages interactive such as


form validation, animation, etc.

 a variable is a container (storage area) to hold data.

 If you use a variable without initializing it, it will have an


undefined value.

 JavaScript is case-sensitive

 null is a special value that represents empty or unknown value.

 JavaScript is a dynamically typed (loosely typed) language.


JavaScript automatically determines the variables' data type for
you.

 type conversion is the process of converting data of one type to


another.

Two types of conversions:

1. JavaScript Implicit Conversion

In certain situations, JavaScript automatically converts


one data type to another (to the right type). This is known as implicit
conversion.

2.JavaScript Explicit Conversion

You can also convert one data type to another as per your needs. The
type conversion that you do manually is known as explicit type
conversion.

In JavaScript, explicit type conversions are done using built-in methods.


a.Number()

In JavaScript, empty strings and null values return 0.

If a string is an invalid number, the result will be NaN.

b.parseInt()

c.parseFloat()

 In programming, loops are used to repeat a block of code.

 The break statement is used to terminate the loop immediately


when it is encountered.

 The continue statement is used to skip the current iteration of the


loop and the control flow of the program goes to the next
iteration.

 If nothing is returned, the function returns an undefined value.

 Function makes the code reusable. You can declare it once and
use it multiple times.

 Scope refers to the availability of variables and functions in


certain parts of the code.

 A variable declared at the top of a program or outside of a


function is considered a global scope variable.

 In JavaScript, a variable can also be used without declaring it. If a


variable is used without declaring it, that variable automatically
becomes a global variable.
 A variable can also have a local scope, i.e it can only be accessed
within a function.

 Hoisting in JavaScript is a behavior in which a function or a


variable can be used before declaration.

 In terms of variables and constants, keyword var is hoisted


and let and const does not allow hoisting.
 However in JavaScript, initializations are not hoisted. For
example,

 // program to display value


 console.log(a);
 var a = 5;
Only the declaration is moved to the memory in the compile phase.
Hence, the value of variable a is undefined because a is printed
without initializing it.

 Also, when the variable is used inside the function, the variable is
hoisted only to the top of the function. For example,
// program to display value
var a = 4;

function greet() {
b = 'hello';
console.log(b); // hello
var b;
}

greet(); // hello
console.log(b)
In the above example, variable b is hoisted to the top of the
function greet and becomes a local variable. Hence b is only accessible
inside the function. b does not become a global variable.

 If a variable is used with the let keyword, that variable is not


hoisted.
 A function can be called before declaring it.

 However, when a function is used as an expression, an error


occurs because only declarations are hoisted.

 Recursion is a process of calling itself. A function that calls itself is


called a recursive function.

 A recursive function must have a condition to stop calling itself.


Otherwise, the function is called indefinitely.

 JavaScript object is a non-primitive data-type that allows you to


store multiple collections of data.

 Three Ways to create objects:

1. Object literal:-

Const person={

“name”:”Vinita”,

“age”:18

2.create object using instance of object directly


Const person=new Object({

“name”:”Vinita”,

“age”:18

})

3.create object using constructor function

function Person() {

this.name=”Vinita”,

this.age=”18”

Const person=new Person();

 In JavaScript, an object can also contain a function. For example,


const person = {

name: 'Sam',

age: 30,

// using function as a value

greet: function() { console.log('hello') }

person.greet(); // hello
 the JavaScript method is an object property that has a function
value like greet is object method.

 You can access an object method using a dot notation. The syntax
is: like objectname.methodkey() ex. person.greet()

 You can also add a method or property in an object. For example,

Create empty object and add properties to object.

// creating an object

let student = { };

// adding a property

student.name = 'John';

// adding a method

student.greet = function() {

console.log('hello');

// accessing a method

student.greet(); // hell
 In JavaScript, this keyword when used with the object's
method refers to the object. this is bound to an object.

 In JavaScript, when this keyword is used in a constructor


function, this refers to the object when the object is created.

 In JavaScript, every function and object has a property named


prototype by default. For example,

 Create Objects: Constructor Function Vs Object Literal


 Object Literal is generally used to create a single object. The
constructor function is useful if you want to create multiple
objects.

 Accessor Property
In JavaScript, accessor properties are methods that get or set the
value of an object. For that, we use these two keywords:

get - to define a getter method to get the property value

set - to define a setter method to set the property value


 JavaScript Getter
In JavaScript, getter methods are used to access the properties
of an object. For example,

const student = {

// data property

firstName: 'Monica',

// accessor property(getter)

get getName() {

return this.firstName;

};

// accessing data property

console.log(student.firstName); // Monica

// accessing getter methods

console.log(student.getName); // Monica
// trying to access as a method
console.log(student.getName()); // error

 JavaScript Setter
 In JavaScript, setter methods are used to change the values of an
object. For example,

const student = {
firstName: 'Monica',

//accessor property(setter)
set changeName(newName) {
this.firstName = newName;
}
};

console.log(student.firstName); // Monica

// change(set) object property using a setter


student.changeName = 'Sarah';

console.log(student.firstName); // Sarah

 An array is an object that can store multiple values at once.

 You can create an array using two ways:

1. Using an array literal:-


The easiest way to create an array is by using an array literal []
Const array1=[“eat”,”sleep”]
2. Using the new keyword
You can also create an array using JavaScript's new keyword.
Const array=new Array(“eat”,”sleep”);
 You can access elements of an array using indices (0, 1, 2 …). For
example,
 You can also add elements or change the elements by accessing
the index value.

 Basically, if you try to add elements to high indices, the indices in


between will have undefined value.

let dailyActivities = [ 'eat', 'sleep'];

// this will add the new element 'exercise' at the 3 index


dailyActivities[3] = 'exercise';

console.log(dailyActivities); // ["eat", "sleep", undefined,


"exercise"]
 You can find the length of an element (the number of elements in
an array) using the length property.

 Array Methods:-

Concat :- joins two or more arrays and returns a result


indexOf():-searches an element of an array and returns its position

find():-
returns the first value of an array element that passes a test

findIndex():-

returns the first index of an array element that passes a test

includes();-

checks if an array contains a specified element

slice():-

selects the part of an array and returns the new array

splice():-
removes or replaces existing elements and/or adds new
elements
 A multidimensional array is an array that contains another
array.
 JavaScript string is a primitive data type that is used to
work with texts.
 Backticks are generally used when you need to include
variables
or expressions into a string. This is done by wrapping
variables or expressions with ${variable or expression}
 In JavaScript, strings are immutable. That means the
characters of a string cannot be changed. For example,

let a = 'hello';
a[0] = 'H';
console.log(a); // "hello"

However, you can assign the variable name to a new


string.

let a = 'hello';
a = 'Hello';
console.log(a); // "Hello"

 The String() function is used to convert various data types


to strings.

 In JavaScript, NaN(Not a Number) is a keyword that indicates that


the value is not a number.
 he built-in function isNaN() can be used to find if a value is a number.

Browser Object Model


The Browser Object Model (BOM) is used to interact with the browser.
The default object of browser is window means you can call all the functions of window by
specifying window or directly.
The window object represents a window in browser. An object of window is created
automatically by the browser.

Window is the object of browser, it is not the object of javascript.


Methods of window object
alert() displays the alert box containing message with ok button.

confirm() displays the confirm dialog box containing message with ok and cancel button.

prompt() displays a dialog box to get input from the user.

open() opens the new window.

close() closes the current window.

setTimeout() performs action after specified time like calling function, evaluating expressions et

JavaScript History Object


The JavaScript history object represents an array of URLs visited by the user. By using this
object, you can load previous, forward or any particular page.

length returns the length of the history URLs.

Methods of JavaScript history object


1 forward( loads the next page.
)

2 back() loads the previous page.

3 go() loads the given page number.

JavaScript Navigator Object


The JavaScript navigator object is used for browser detection. It can be used to get browser
information such as appName, appCodeName, userAgent etc.
Property of JavaScript navigator object
1 appName returns the name

2 appVersion returns the version

3 appCodeName returns the code name

4 cookieEnabled returns true if cookie is enabled otherwise false

5 userAgent returns the user agent

6 language returns the language. It is supported in Netscape and Firefox only.

7 userLanguage returns the user language. It is supported in IE only.

8 plugins returns the plugins. It is supported in Netscape and Firefox only.

9 systemLanguage returns the system language. It is supported in IE only.

10 mimeTypes[] returns the array of mime type. It is supported in Netscape and Firefox o

11 platform returns the platform e.g. Win32.

12 online returns true if browser is online otherwise false.

Methods of JavaScript navigator object


1 javaEnabled() checks if java is enabled.

2 taintEnabled() checks if taint is enabled. It is deprecated since JavaScript 1.2.

JavaScript Screen Object


The JavaScript screen object holds information of browser screen. It can be used to display
screen width, height, colorDepth, pixelDepth etc.

1 width returns the width of the screen

2 height returns the height of the screen


3 availWidth returns the available width

4 availHeight returns the available height

5 colorDepth returns the color depth

6 pixelDepth returns the pixel depth.

Types of Errors
Syntax Error: Error in the syntax. For example, if you write consol.log('your

result'); , the above program throws a syntax error. The spelling of console is
a mistake in the above code.

Runtime Error: This type of error occurs during the execution of the
program. For example,
calling an invalid function or a variable.
These errors that occur during runtime are called exceptions.

JavaScript try...catch Statement


The try...catch statement is used to handle the exceptions.
The main code is inside the try block. While executing the try block, if any
error occurs, it goes to the catch block. The catch block handles the errors as
per the catch statements.
The finally block executes both when the code runs successfully or if an
error occurs.
the throw statement handles user-defined exceptions.
Module is a file that contains code to perform a specific task. A module may
contain variables, functions, classes etc.

// exporting the variable


export const name = 'JavaScript Program';

// exporting the function


export function sum(x, y) {
return x + y;
}

mport { name, sum } from './module.js';

console.log(name);
let add = sum(4, 9);
console.log(add); // 13

Renaming imports and exports


To avoid naming conflicts, you can rename these functions, objects, etc.
during the export or during the import .

1. Rename in the module (export file)

// renaming import inside module.js


export {
function1 as newName1,
function2 as newName2
};

// when you want to use the module


// import in the main file
import { newName1, newName2 } from './module.js';
2. Rename in the import file

/ inside module.js
export {
function1,
function2
};

// when you want to use the module


// import in the required file with different name

import { function1 as newName1, function2 as newName2 } from './module.js';

Default Export
You can also perform default export of the module. For example,

In the file greet.js:

// default export
export default function greet(name) {
return `Hello ${name}`;
}

export const age = 23;

Then when importing, you can use:

import random_name from './greet.js';

You can directly use the default export without enclosing curly brackets {} .

this with Arrow Function


Inside a regular function, this keyword refers to the function where it is called.
However, this is not associated with arrow functions. Arrow function does not
have its own this . So whenever you call this , it refers to its parent scope.

Arrow functions do not have arguments binding.

1. You should not use arrow functions to create methods inside objects.
2. You cannot use an arrow function as a constructor. For example,

Template Literals:-
Template literals (template strings) allow you to use strings or embedded
expressions in the form of a string. They are enclosed in backticks ``

Template literals also make it easy to write multiline strings.


With template literals, it's a bit easier to include variables and expressions
inside a string. For that, we use the ${...}

The process of assigning variables and expressions inside the template literal
is known as interpolation.

Js Spread Operator:-
The spread operator ... is used to expand or spread an iterable or an array.
You can also use the spread syntax ... to copy the items into a single array
if you want to copy arrays so that they do not refer to the same array, you can
use the spread operator. This way, the change in one array is not reflected in
the other.
Rest Parameter
When the spread operator is used as a parameter, it is known as the rest
parameter.
You can also accept multiple arguments in a function call using the rest
parameter.
For Example:-
let func = function(...args) {
console.log(args);
}

func(3); // [3]
func(4, 5, 6); // [4, 5, 6]

JS Map:-
Map is similar to objects in JavaScript that allows us to store elements in
a key/value pair.
To create a Map , we use the new Map() constructor. For example,
// create a Map
const map1 = new Map(); // an empty map
console.log(map1); // Map {}

After you create a map, you can use the set() method to insert elements to
it.
// create a set
let map1 = new Map();

// insert key-value pair


map1.set('info', {name: 'Jack', age: 26});
console.log(map1); // Map {"info" => {name: "Jack", age: 26}}
You can also use objects or functions as keys. For example,
// Map with object key
let map2 = new Map();

let obj = {};


map2.set(obj, {name: 'Jack', age: "26"});

console.log(map2); // Map {{} => {name: "Jack", age: "26"}}

You can access Map elements using the get() method. For example,
let map1 = new Map();
map1.set('info', {name: 'Jack', age: "26"});

// access the elements of a Map


console.log(map1.get('info')); // {name: "Jack", age: "26"}

You can use the has() method to check if the element is in a Map. For
example,

You can use the has() method to check if the element is in a Map. For
example,

const set1 = new Set([1, 2, 3]);

let map1 = new Map();


map1.set('info', {name: 'Jack', age: "26"});

// check if an element is in Set


console.log(map1.has('info')); // true
You can use the clear() and the delete() method to remove elements from a
Map.
The delete() method returns true if a specified key/value pair exists and has
been removed or else returns false . For example,

let map1 = new Map();


map1.set('info', {name: 'Jack', age: "26"});

// removing a particular element


map1.delete('address'); // false
console.log(map1); // Map {"info" => {name: "Jack", age: "26"}}

map1.delete('info'); // true
console.log(map1); // Map {}
The clear() method removes all key/value pairs from a Map object. For
example,
let map1 = new Map();
map1.set('info', {name: 'Jack', age: "26"});

// removing all element


map1.clear();
console.log(map1); // Map {}

You can get the number of elements in a Map using the size property. For example,
let map1 = new Map();
map1.set('info', {name: 'Jack', age: "26"});
console.log(map1.size); // 1

You can iterate through the Map elements using the for...of loop
or forEach() method. The elements are accessed in the insertion order. For
example,
let map1 = new Map();
map1.set('name', 'Jack');
map1.set('age', '27');

// looping through Map


for (let [key, value] of map1) {
console.log(key + '- ' + value);
}

You can iterate over the Map and get the key using the keys() method. For
example,
let map1 = new Map();
map1.set('name', 'Jack');
map1.set('age', '27');

// looping through the Map


for (let key of map1.keys()) {
console.log(key)
}

You can iterate over the Map and get the values using the values() method.
For example,
let map1 = new Map();
map1.set('name', 'Jack');
map1.set('age', '27');

// looping through the Map


for (let values of map1.values()) {
console.log(values);
}

Map Object

Maps can contain objects and other data Objects can only contain strings and symbols
types as keys. as keys.

Maps can be directly iterated and their value


Objects can be iterated by accessing its keys.
can be accessed.

The number of elements of a Map can be The number of elements of an object needs to
determined by size property. be determined manually.

Map performs better for programs that Object does not perform well if the program
require the addition or removal of elements requires the addition or removal of elements
frequently. frequently.

JavaScript WeakMap
The WeakMap is similar to a Map. However, WeakMap can only contain
objects as keys. For example,

const weakMap = new WeakMap();


console.log(weakMap); // WeakMap {}

let obj = {};


// adding object (element) to WeakMap
weakMap.set(obj, 'hello');

console.log(weakMap); // WeakMap {{} => "hello"}

When you try to add other data types besides objects, WeakMap throws an
error.
const weakMap = new WeakMap();

// adding string as a key to WeakMap


weakMap.set('obj', 'hello');

WeakMaps have methods get() , set() , delete() , and has() . For example,
const weakMap = new WeakMap();
console.log(weakMap); // WeakMap {}

let obj = {};

// adding object (element) to WeakMap


weakMap.set(obj, 'hello');

console.log(weakMap); // WeakMap {{} => "hello"}

// get the element of a WeakMap


console.log(weakMap.get(obj)); // hello

// check if an element is present in WeakMap


console.log(weakMap.has(obj)); // true
// delete the element of WeakMap
console.log(weakMap.delete(obj)); // true

console.log(weakMap); // WeakMap {}

Unlike Maps, WeakMaps are not iterable.

Javascript Set:-
Set is similar to an array that allows us to store multiple items like numbers,
strings, objects, etc. However, unlike an array, a set cannot contain duplicate
values.

To create a Set , you need to use the new Set() constructor. For example,
// create Set
const set1 = new Set(); // an empty set
console.log(set1); // Set {}

// Set with multiple types of value


const set2 = new Set([1, 'hello', {count : true}]);
console.log(set2); // Set {1, "hello", {count: true}}

When duplicate values are passed to a Set object, the duplicate values are
excluded.
// Set with duplicate values
const set3 = new Set([1, 1, 2, 2]);
console.log(set3); // Set {1, 2}
You can access Set elements using the values() method and check if there is
an element inside Set using has() method. For example,
const set1 = new Set([1, 2, 3]);

// access the elements of a Set


console.log(set1.values()); // Set Iterator [1, 2, 3]

You can use the has() method to check if the element is in a Set. For
example,
const set1 = new Set([1, 2, 3]);

// check if an element is in Set


console.log(set1.has(1));
You can add elements to a Set using the add() method. For example,
const set = new Set([1, 2]);
console.log(set.values());

// adding new elements


set.add(3);
console.log(set.values());

// adding duplicate elements


// does not add to Set
set.add(1);
console.log(set.values());

The delete() method removes a specific element from a Set .

const set = new Set([1, 2, 3]);


console.log(set.values()); // Set Iterator [1, 2, 3]

// removing a particular element


set.delete(2);
console.log(set.values()); // Set Iterator [1, 3]

The clear() method removes all elements from a Set .

You can iterate through the Set elements using the for...of loop
or forEach() method. The elements are accessed in the insertion order.
const set = new Set([1, 2, 3]);

// looping through Set


for (let i of set) {
console.log(i);
}

JavaScript WeakSet
The WeakSet is similar to a Set. However, WeakSet can only contain objects
whereas a Set can contain any data types such as strings, numbers, objects,
etc.

const weakSet = new WeakSet();


console.log(weakSet); // WeakSet {}

let obj = {
message: 'Hi',
sendMessage: true
}
// adding object (element) to WeakSet
weakSet.add(obj);

console.log(weakSet); // WeakSet {{message: "Hi", sendMessage:


true}}

When you try to add other data types besides objects, WeakSet throws an
error.

WeakSets have methods add() , delete() , and has() . For example,


const weakSet = new WeakSet();

console.log(weakSet); // WeakSet {}

const obj = {a:1};

// add to a weakSet

weakSet.add(obj);

console.log(weakSet); // WeakSet {{a: 1}}

// check if an element is in Set

console.log(weakSet.has(obj)); // true
// delete elements

weakSet.delete(obj);

console.log(weakSet); // WeakSet {}

Unlike Sets, WeakSets are not iterable.

JavaScript Destructuring
The destructuring assignment introduced in ES6 makes it easy to assign
array values and object properties to distinct variables.

// assigning object attributes to variables

const person = {

name: 'Sara',

age: 25,

gender: 'female'

// destructuring assignment

let { name, age, gender } = person;


console.log(name); // Sara

console.log(age); // 25

console.log(gender); // female

The order of the name does not matter in object destructuring.

When destructuring objects, you should use the same name for the variable
as the corresponding object key.

If you want to assign different variable names for the object key, you can use:

const person = {

name: 'Sara',

age: 25,

gender: 'female'

// destructuring assignment

// using different variable names

let { name: name1, age: age1, gender:gender1 } = person;

console.log(name1); // Sara
console.log(age1); // 25

console.log(gender1); // female

Array Destructuring
You can also perform array destructuring in a similar way. For example,

const arrValue = ['one', 'two', 'three'];

// destructuring assignment in arrays

const [x, y, z] = arrValue;

console.log(x); // one

console.log(y); // two

console.log(z); // three

You can skip unwanted items in an array without assigning them to local
variables. For example,

const arrValue = ['one', 'two', 'three'];

// destructuring assignment in arrays

const [x, , z] = arrValue;


console.log(x); // one

console.log(z); // three

JavaScript Classes
A class is a blueprint for the object. You can create an object from the class.

The class keyword is used to create a class. The properties are assigned in a
constructor function.

// creating a class
class Person {
constructor(name) {
this.name = name;
}
}

// creating an object
const person1 = new Person('John');
const person2 = new Person('Jack');

console.log(person1.name); // John
console.log(person2.name); // Jack

It is easy to define methods in the JavaScript class. You simply give the name
of the method followed by ()

In JavaScript, getter methods get the value of an object and setter methods
set the value of an object.

You use the get keyword for getter methods and set for setter methods.
class Person {
constructor(name) {
this.name = name;
}

// getter
get personName() {
return this.name;
}

// setter
set personName(x) {
this.name = x;
}
}

let person1 = new Person('Jack');


console.log(person1.name); // Jack

// changing the value of name property


person1.personName = 'Sarah';
console.log(person1.name); // Sarah

A class should be defined before using it. Unlike functions and other
JavaScript declarations, the class is not hoisted.
Classes always follow 'use-strict'. All the code inside the class is
automatically in strict mode.

JavaScript class is a special type of function. And the typeof operator


returns function for a class.

Js Prototype:-
What is the requirement of a prototype
object?
Whenever an object is created in JavaScript, its corresponding functions are loaded into
memory. So, a new copy of the function is created on each object creation.

In a prototype-based approach, all the objects share the same function. This ignores the
requirement of creating a new copy of function for each object. Thus, the functions are loaded
once into the memory.

JavaScript Constructor Method


A JavaScript constructor method is a special type of method which is used to initialize
and create an object. It is called when memory is allocated for an object.

o The constructor keyword is used to declare a constructor method.


o The class can contain one constructor method only.
o JavaScript allows us to use parent class constructor through super keyword.
Note - If we didn't specify any constructor method, JavaScript use default
constructor method.

JavaScript static Method


The JavaScript provides static methods that belong to the class instead of an instance
of that class. So, an instance is not required to call the static method. These methods
are called directly on the class itself.

o The static keyword is used to declare a static method.


o The static method can be of any name.
o A class can contain more than one static method.
o If we declare more than one static method with a similar name, the JavaScript
always invokes the last one.
o The static method can be used to create utility functions.
o We can use this keyword to call a static method within another static method.
o We cannot use this keyword directly to call a static method within the non-static
method. In such case, we can call the static method either using the class name
or as the property of the constructor.
JavaScript Encapsulation
The JavaScript Encapsulation is a process of binding the data (i.e. variables) with the
functions acting on that data. It allows us to control the data and validate it. To achieve
an encapsulation in JavaScript: -

o Use var keyword to make data members private.


o Use setter methods to set the data and getter methods to get that data.

Class Inheritance:-
Using class inheritance, a class can inherit all the methods and properties of
another class.

To use class inheritance, you use the extends keyword.

The super keyword used inside a child class denotes its parent class.

If a child class has the same method or property name as that of the parent
class, it will use the method and property of the child class. This concept is
called method overriding.

JavaScript Polymorphism
The polymorphism is a core concept of an object-oriented paradigm that provides a
way to perform a single action in different forms.

JavaScript Abstraction
An abstraction is a way of hiding the implementation details and showing only the
functionality to the users. In other words, it ignores the irrelevant details and shows
only the required one.

o We cannot create an instance of Abstract Class.


o It reduces the duplication of code.

JavaScript Proxies
proxies (proxy object) are used to wrap an object and redefine various
operations into the object such as reading, insertion, validation, etc. Proxy
allows you to add custom behavior to an object or a function.

the syntax of proxy is:

new Proxy(target, handler);

Here,

 new Proxy() - the constructor.


 target - the object/function which you want to proxy
 handler - can redefine the custom behavior of the object

Javascript setTimeout()
The setTimeout() method executes a block of code after the specified time.
The method executes the code only once.
The commonly used syntax of JavaScript setTimeout is:
setTimeout(function, milliseconds);

Its parameters are:

 function - a function containing a block of code


 milliseconds - the time after which the function is executed
The setTimeout() method returns an intervalID, which is a positive integer.

JavaScript clearTimeout()
As you have seen in setTimeOut, the program executes a block of code after
the specified time interval. If you want to stop this function call, you can use
the clearTimeout() method.
The syntax of clearTimeout() method is:

clearTimeout(intervalID);

Here, the intervalID is the return value of the setTimeout() method.

You can also pass additional arguments to the setTimeout() method. The
syntax is:

setTimeout(function, milliseconds, parameter1, ....paramenterN);

When you pass additional parameters to the setTimeout() method, these


parameters ( parameter1 , parameter2 , etc.) will be passed to the
specified function.
JavaScript CallBack Function
In JavaScript, you can also pass a function as an argument to a function.
This function that is passed as an argument inside of another function is
called a callback function.

// function
function greet(name, callback) {
console.log('Hi' + ' ' + name);
callback();
}

// callback function
function callMe() {
console.log('I am callback function');
}

// passing function as an argument


greet('Peter', callMe);

The benefit of using a callback function is that you can wait for the result of a
previous function call and then execute another function call.

JavaScript Promise and Promise


Chaining
In JavaScript, a promise is a good way to handle asynchronous operations.
It is used to find out if the asynchronous operation is successfully completed
or not.
A promise may have one of three states.

 Pending

 Fulfilled

 Rejected

A promise starts in a pending state. That means the process is not complete.
If the operation is successful, the process ends in a fulfilled state. And, if an
error occurs, the process ends in a rejected state.

Create a Promise
To create a promise object, we use the Promise() constructor.
The Promise() constructor takes a function as an argument. The function also
accepts two functions resolve() and reject() .

If the promise returns successfully, the resolve() function is called. And, if an


error occurs, the reject() function is called.
const count = true;

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


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

JavaScript Promise Chaining


Promises are useful when you have to handle more than one asynchronous
task, one after another. For that, we use promise chaining.

You can perform an operation after a promise is resolved using


methods then() , catch() and finally() .

You might also like