0% found this document useful (0 votes)
1 views119 pages

Javascript Guide

This document provides a comprehensive guide to JavaScript, covering topics such as integrating JavaScript with HTML, variable declaration, data types, operators, loops, functions, and the Document Object Model (DOM). It explains the differences between primitive data types and objects, the use of various DOM selectors, and methods for manipulating elements within the DOM. Additionally, it delves into asynchronous JavaScript, including callbacks, promises, and the async/await syntax.

Uploaded by

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

Javascript Guide

This document provides a comprehensive guide to JavaScript, covering topics such as integrating JavaScript with HTML, variable declaration, data types, operators, loops, functions, and the Document Object Model (DOM). It explains the differences between primitive data types and objects, the use of various DOM selectors, and methods for manipulating elements within the DOM. Additionally, it delves into asynchronous JavaScript, including callbacks, promises, and the async/await syntax.

Uploaded by

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

Javascript

By Nirbhay
TABLE OF CONTENTS
Integrating javascript
Use of [Link]
Javascript Variables
var vs let in javascript
Primitive data types & objects
Object
Everything Else is an Object
Operators in js
Javascript loops
Javascript functions
Arrow function
Let’s break down arrow function syntax
Javascript strings
Javascript arrays
Looping through arrays
map
filter
reduce
[Link]
Document Object Model
Tree Structure
DOM Selectors
getElementById
getAttribute
setAttribute
Inserting style using DOM
textContent
innerHTML & innerText
innerText vs textContent
innerText
textContent
getElementsByClassName()
querySelector
Query selector on Unordered list
querySelectorAll
NodeList
HTMLCollection
Manipulating values using DOM
To find list of children of a class
Other important properties
1. firstElementChild
2. lastElementChild
3. parentElement
4. nextElementSibling
5. childNodes
Creating Element & NodeList using DOM
createElement()
Setting different attributes like class, id to the
element using DOM
Setting custom attributes
Attaching the element to document
createTextNode()
Adding node to the newly created element
Use of appendChild()
Now, we can attach the element to the document.
Editing elements in DOM
IMPORTANT: Optimization appendChild() method
replaceWith()
Removing elements in DOM
Events in Javascript
Using addEventListener()
What happens inside Event:
List of Events to study
Event Propagation
stopPropagation()
preventDefault()
A simple task related to Events
Explanation of the above code:
Use of parentNode
Use of remove() function
removeChild()
Use of tagName
Async Javascript
Blocking code vs Non blocking code
Blocking Code
Non blocking code
IMPORTANT: JavaScript Execution Model
1. JavaScript Engine
2. Web API
3. Promises and High-Priority Queue
4. Task Queue
5. Event Loop
IMPORTANT:
Asynchronous nature of Javascript
Javascript Callbacks
Javascript Promises
Three states of promise
Why Promises Are Not for Synchronous Tasks:
What Happens If You Use a Promise for a
Synchronous Task?
Clarification on what is Promise actually
Is promise an object or a class or a constructor or a
function? What is it actually?
Creation of promises
Now consuming the promise:
If we don’t call resolve() inside promise object
resolve()
Parameters Passed to resolve()
reject()
Parameters passed to reject()
.then()
.catch()
Handling errors in promise object
Not storing the promise object in a variable
Chaining in promise
Use of .finally()
Async/Await
fetch()
Integrating javascript
There are two ways to integrate javascript to html
document in frontend:
1.​ Writing javascript code directly in an html document
in the <script> tag.
See like this:

2.​Linking “.js” file to your HTML file, use this syntax in your
HTML file:

[Link]: Replace this with the name of your


.js file.
See the image below:
Use of [Link]

This can be used to check status of execution & helps in debugging.

Javascript Variables
Rules for choosing variable names in Java script:

1.​ Start with a letter, $, or _:​


Variable names must begin with:
●​ A letter (a-z or A-Z).
●​ A dollar sign ($).
●​ An underscore (_)
2.​Case-sensitive:​
Variable names are case-sensitive.​
Example:
var myVariable = 10;
var MyVariable = 20; // Different variable
3.​No reserved keywords:Variable names cannot use
JavaScript reserved keywords like var, let, const,
function, if, else, etc.
4.​Avoid starting with numbers:While numbers are
allowed in variable names, they cannot be the first
character.

var vs let in javascript ← click IT TO KNOW MORE

5.​const a1=6; a1=a1+1; this assignment not allowed as a1


is constant, but with let & var it is allowed.
Primitive data types & objects

●​ Primitives are immutable.


Object
In javascript objects are key-value pairs:

●​ Objects are mutable


●​ keys are strings and the values can be any data type

➢​For more visit the link.

But, also objects are more than just being traditional key-value pairs.
See:

In JavaScript, everything is either:

1.​ Primitive (immutable values)


2.​Object (everything else)

In javascript, except 7 primitive data types, everything


else is an object.

Everything Else is an Object


Objects are mutable and stored by reference:​
✅ Objects → { name: "Alice" }​
✅ Arrays → [1, 2, 3]​
✅ Functions → function() {} (functions are objects)​
✅ Classes → class MyClass {} (syntactic sugar for
constructor functions)​
✅ Dates → new Date()​
✅ Regular Expressions → /abc/​
✅ Maps & Sets → new Map(), new Set()​
✅ Errors → new Error("Oops")​
✅ Prototypes and instances of objects
It means arrays, functions, classes all are objects.

In this case one question might arise:

As seen in the above image & it is said that an object in javascript is a


key value pair. But functions or classes are not key value pairs, then
how can they be an object ?

Answer: Note in JavaScript, objects are more than just key-value


pairs. Functions and classes are objects because they have properties
and methods, even if they don’t look like traditional key-value objects.
Clarification of line: “[Link]([Link])”
Classes are also objects.

We have seen in javascript functions and classes have


various built-in properties. And we have seen javascript
treats these functions or classes as objects.

One statement is there inside the red box of the image under
the topic “Functions are Objects” : “since functions are
objects in JavaScript, they have built-in properties.” From
this statement a question arises:
it means if functions were not treated as objects, they would not have
built-in properties ?

Answer:

For more on objects: click here


Javascript Conditionals: if, if-else

Output:
●​ This semicolon at the end of line is optional in
javascript.

Operators in js

See: “3”==3 gives true but “3”===3 gives false as output.


Javascript loops
Similar to c++ loops
Only extras are for-in loop & for-of loop.

Output:

Javascript functions
These are similar to c++ functions.
For more: click

Arrow function
Syntax:

Or for multiple lines :


●​ See the syntax of arrow function carefully.

The phrase "explicit return required" means that in


some cases, you must manually use the return
keyword to return a value from a function.

Look at these carefully below :


Let’s break down arrow function syntax
The arrow function syntax:

The traditional function syntax :


Now, let’s compare each part of both the syntaxes to
each other:

Example Comparison
Again see the comparison:

Summary:
One more thing to notice :

In javascript functions

Similarly applies for traditional functions :


Calling the function (arrow or traditional) :
It means the variable which is storing the function is acting as the
name of the function while calling.

For better clarification : just click here


“ this in javascript

Javascript strings
Click here
Javascript arrays

output:

●​ Arrays are mutable

●​ [Link](typeof arr) gives object as array in js is object


type.
Array functions:
For more: click
A normal for loop on array:

See:
Looping through arrays
map
Creates a new array by performing some operations on the
original array in one line efficient than using “for loop” for
such task.
Using for loop:

But, this can be done in a very easy way by using map()


filter
reduce

[Link]
Document Object Model

See title of the page is now


Welcome

The DOM (Document Object Model) in JavaScript is a


programming interface that represents the structure of
an HTML or XML document as a tree of objects. It allows
JavaScript to interact with and manipulate the content,
structure, and style of a webpage dynamically.

Tree Structure

Document object model for the above html document:


To access a child or any element of document and get it
directly in console:
[Link]([Link])
See eg.,
●​ HTML Collection, Node collection these are not
arrays. Yeah, these can be converted into arrays.
●​ So, properties of array like map(), for each() …
are not applicable to these.

DOM Selectors
Various methods/functions of the document object in JS:
getElementById
Syntax: getElementById(‘idName’)

Ab iss element <h1> ke andar ke alag alag elements ko


select kar sakte hain.

Ab jaise <h1> element jise humne uske id ‘title’ se


access kiya uska class ka value janane ya class access
karne ke liye ke liye see:

getAttribute

setAttribute
Inserting style using DOM

title is a DOM object which can be used in place of getElementById(‘title’)


This is a way of inserting inline style:

textContent
To extract content or values from an element:

innerHTML & innerText

But, innerHTML, textContent, innerText all are different.


innerText vs textContent

innerText
1.​ It retrieves or sets only the text that is visible to
the user. This means it excludes hidden elements
(e.g., those with display: none or visibility:
hidden).
2.​Normalizes whitespace, removing extra spaces and
line breaks.
3.​Performance: Slightly slower because it requires
layout calculations to determine what is visible on the
page.

textContent
1.​ Retrieves or sets all the text content of an element,
including hidden elements.
2.​Preserves whitespace exactly as it is in the DOM.
3.​Performance: Faster because it directly works with
the DOM without considering styles or layout.
Now, humlog ab <span> me display: none; property add
karte hain aur tab dekhte hain:

Now see the difference:

Now see innerHTML:


getElementsByClassName()
The getElementsByClassName method is a DOM
(Document Object Model) method that retrieves all
elements in the document (or within a specific element)
that have a particular class name.

Syntax:
classNames: A string that specifies the class name(s) to
search for. Multiple class names can be specified,
separated by spaces.
●​ returns a live HTMLCollection of all matching elements.
See HTMLCollection looks like this:

querySelector
It allows you to retrieve the first element that matches a
specified selector or selectors within the document or a
specific parent element.
Syntax:
Parameters:
●​ selectors: A string containing one or more CSS
selectors (e.g., class, id, tag, attribute selectors, or
combinators).
Returns:
●​ The first element in the document that matches the
specified selector(s), or null if no match is found.
See my code:

Query selector on Unordered list


Using querySelector(), first element of the list can be selected.
querySelectorAll

Syntax:

●​ selects all elements in the document (or a specific


parent element) that match a specified CSS
selector(s).
●​ returns a NodeList.
NodeList
●​ NodeList is not an proper array.

Output:

But in the NodeList there are some prototypes similar to arrays


like for-each loop
for each loop:
For syntax: click here

getElementsByClassName

HTMLCollection
●​ HTMLCollection is different from arrays.
●​ Its prototype/methods/functions do not match with
arrays.
●​ Eg., for each loop will give error if applied on HTMLCollection
●​ But classic normal for loop with work on HTMLCollection as
well as NodeList as it works anything which is array like.
To use loops like for-each, arrays functions like map(), we need
to convert HTMLCollection to arrays:
Use [Link](objectName which is to be converted to array)

Now you will see the prototype will contain all the same
functions/loops that are for arrays.
For eg.,
Now we can apply for-each loop on that collection:
See forEach loop applied, color changed to orange:
Manipulating values using DOM
To find list of children of a class
See main program:

Use of [Link]

●​ In
●​ “parent” with no. 2 is the class
●​ “parent” with no. 1 is the object which refers to the element
selected by querySelector (here that element is this <div>)
for the class=”parent”.
●​
●​ In [Link](parent), me jo parent hai wah object wala parent
hai.
●​ Since parent object uss element ko refer karta hai
isiliye [Link](parent) uss element ka pura body
as result de deta hai. See the image below:
●​ “[Link]” gives HTMLCollection of the
children of the element selected by querySelector
(here that element is this <div>).

See the HTMLCollection as output:

See more:

Gives member at index 1 in html collection. See:

Also see:

See output:
Applying “for” loop on the HTMLCollection obtained from
[Link]. See:

See output will be like this a vertical list of innerHTML


content of all the elements present in the HTMLCollection
of “[Link]”:

Other important properties


There are many other properties that can be applied on
the element selected by querySelector()
See:
1.​ firstElementChild

See output:

2.​lastElementChild

Output:
Gives last child(element) of the element selected by
querySelector(.parent) which is referred by parent object.
3.​parentElement

“[Link]” gives the parent element of


the element stored in “dayOne” object.
See the output displays the parent:

4.​nextElementSibling
Syntax: element( or object storing an
element).nextElementSibling
Gives the element next to the element stored in the
dayOne object.
Output:

5.​childNodes
Syntax:

Now, “[Link]” returns a NodeList of


children of that element which is stored by this
parent object.
●​ Gives the complete tree as Nodelist
Creating Element & NodeList using DOM
How NodeList is created?

createElement()
●​ used to create an element node with a specified tag
name (e.g., div, p, span).
●​ Also, you can create an element node with any tag
name(my-element or any arbitrary word) using the
createElement() method.
●​ But these elements will still be part of the DOM, but
browsers treat them as generic unknown elements
unless additional logic is defined using css or js.
●​ The only difference with words (custom tag Names)
other than predefined tagNames is that there will be
no predefined styling in elements (custom elements)
created by those words.
●​ The text or content inside those custom elements will
be displayed as plain text.
●​ We can define their styling by using our own css or
js.
●​ NOTE that createElement() does create an element,
it creates a node (element node) in the DOM tree.
●​ This element node represents an HTML element that
can later be appended to the DOM and interact with
other elements. Click on this point.
Syntax:

●​ tagName: A string representing the type of element


to create (e.g., 'div', 'span', 'p', etc.).

●​ Eg., [Link](‘div’) : an empty


element <div></div> will be created.

See the output below: <div> element created. Looks


like <div></div>
See output:

Setting different attributes like class, id to the


element using DOM
Setting custom attributes
Syntax:
[Link](“attributeName”,”attributeValue”)
See:

After adding various attributes & properties to newly


created element:

But these properties are being displayed only in console


not on the web page. See:

●​ This is because the newly created <div> is in memory


only but not attached to the document.
●​ So, we have to attach/ append the element to the
document.

Attaching the element to


document
Before knowing how to attach/append an element to
document, study these:

createTextNode()
●​ used to create a text node, which represents a string
of text to be added to an HTML document.

Syntax:

Using createTextNode is better than innerText as


createTextNode is more efficient.

createTextNode():

●​ More efficient when adding pure text content since


it doesn't involve re-parsing or recalculating the
element's structure.

innerText:
●​ Can be slower because it involves more processing
(e.g., layout recalculations if styles like display:
none affect visibility).

Adding node to the newly created element

Use of appendChild()
●​ used to add a node (such as an element or text) as
the last child of a specified parent node.
●​ It's a common method in the DOM API for
manipulating elements dynamically.
Syntax:
●​ parentNode: The parent element to which the new
child node will be appended.
●​ newChild: The node you want to append as the last
child.

Now, we can attach the element to the document.


To understand this part first read all the above parts
under Attaching the element to document topic.

Syntax: [Link](element)
Now see all the properties of <div> are being displayed on
the webpage.
Editing elements in DOM
1.​ Adding new element Node in the DOM tree and
adding new items or content or text to it.

IMPORTANT: Optimization appendChild() method


This method traverses the complete DOM tree every time
when it is called by a function.
Say, here in above pic addLanguage(“python”) is function
call which calls appendChild(newNode) which traverses the
complete DOM tree from top in order to append a
newNode(here ‘li’ variable which is written just after
const) at its specified place.
Now if we again call the function, appendChild() will again
traverse the whole tree starting from top.
So, This is not optimized approach.
See:
Optimized Approach:

2.​ Editing the content of the element in the DOM tree.

replaceWith()
For more with replaceWith(): click

Removing elements in DOM


Events in Javascript
1st approach: Not good approach

But the above approach of writing “onclick” there, after


‘alt’ is not feasible & good for the above task.
So, use this 2nd approach: good approach

But, this 2nd approach also has some problem. This


provides less features.
Let’s see this 3rd approach: best approach

Using addEventListener()
This is the best method.

What happens inside Event:

On executing above code: [Link](e), we get;


Here in the list of events under pointerEvent we get
various events like browser events, environment events.
Jaise where mouse clicked, what was the position of
mouse pointer, all these details related to these events
we get in this list.
●​ In interviews generally questions related to this are
asked like konsa view tha, jis time apne click kiya to
batato window ki height & width kya thi, ya phir kis
time pe click hua (timeStamp) batao.
●​ Basic questions diye jate hain interviews me like ek
application bana ke dikhao jahan pe jis time pe bhi iss
image pe ya phir kahin bhi jaise body me click kar
raha hai to uska time bata de.
●​ Kai bar aise questions aate hain ki ek application
banao jahan pe ek div ho, uss div me main jahan pe bhi
click karoon wahan pe ek circle create ho jaye.

➢​NOTE: ye upar ke saare questions event se hi


honge. Koi react waigara nahi lagega isme.
List of Events to study

Event Propagation
See the output in console:

But, in place of “false” if we write “true”, result is just


opposite.

See the result:

To stop bubbling:
stopPropagation()

See result:

preventDefault()

For such cases we use preventDefault()


See:
Here, that element is under the id=”google”.
And the default behaviour is that when we click on the
text ‘Google’ written on web page, it redirection us to
google website( [Link]). We don’t want it to happen.
So, we will have to stop/prevent that default behaviour.
So, we are using preventDefault() method/function.

See the result of execution of above code:

Preventing bubbling: stopPropagation()

See the output:


A simple task related to Events
Now, see how to do the above task:

Explanation of the above code:


For its explanation: click here.
Use of parentNode

●​ e is the event object, and [Link] is the DOM


node where the click originated.
●​ Parent node of ‘[Link]’ is selected using this line of
code: “[Link]([Link]); “

On expanding that parent node, inside we will get the


target of the image ( obtained using [Link]). See:
Use of remove() function

removeIt variable stores the compete parent <li> ( see


above img) of [Link]. So, when we apply remove()
method on removeIt, the compete <li> element gets
removed & no space is left.
See on clicking the image:
For video : click here.
Instead of remove() function we can also use
removeChild(). See:

removeChild()

[Link]: Refers to the parent of the


element you want to remove.

[Link](removeIt):

●​ This tells the browser, "Hey, take the parent of the


removeIt element, and remove removeIt from it."
●​ The above code line means ki parent ko bola ja raha
hai ki hey parent tum apne child ko remove kardo.
Yaani removeIt ke ke parent ko bola ja rha hai ki tum
apne child yani removeIt ko remove kar do apne me
se.
For more explanation of the above code: click here.

But there is still one problem.

See problem on executing the code:

For video of this part: click here


Image pe click kiya to since uska parent <li> element hai to
sirf <li> hi remove hua.
But, if click on <li> directly ( any list item say ‘Google’ for
eg.), since its parent is <ul> itself so complete <ul> will be
removed. So, we see everything gets removed.

To address this problem:


Using some conditions & checks like if we can solve it.
See:

Use of tagName

For video part of this: click here


Async Javascript

Javascript is:
●​ Synchronous
●​ Single threaded

●​ Single Threaded: JavaScript has only one call stack,


so it can perform only one operation at a time.
●​ Synchronous: Code is executed sequentially, line by
line. Each task must finish before the next one
starts.
Blocking code vs Non blocking
code

Blocking Code
●​ Blocks the flow of program
●​ Read file sync

Non blocking code


●​ Does not block execution
●​ Read file async

To see examples of blocking vs non blocking code and know


which is better : click here

●​ Which is best here depends on situations & use cases


IMPORTANT: JavaScript Execution Model

Explanation:

1. JavaScript Engine
●​ The JS Engine is where the JavaScript code runs. It
has two key components:
○​ Memory Heap:
■​ Used for storing variables, objects, and
functions in memory.
○​ Call Stack:
■​ A stack data structure that keeps track of
function calls.
■​ Functions are executed in a Last In, First
Out (LIFO) order.
■​ When a function is called, it is added
(pushed) to the stack.
■​ Once execution is complete, it is removed
(popped) from the stack.

2. Web API
●​ This part represents the browser's environment
(outside the JS Engine) that provides additional
features like:
○​ DOM Manipulation APIs: For interacting with
the webpage.
○​ Timers: setTimeout and setInterval.
○​ Fetch API: For network requests.
○​ These APIs run asynchronously and register
callbacks in the background.

3. Promises and High-Priority Queue


●​ Promises represent asynchronous operations in
modern JavaScript.
●​ Promises are given higher priority compared to
regular tasks in the task queue.

We will study about promises in detail later on.


4. Task Queue
●​ This is a queue where callbacks from asynchronous
operations (e.g., setTimeout) are placed once their
respective operations are complete.
●​ The Event Loop ensures that:
1.​ The Call Stack is empty.
2.​Tasks from the Task Queue are moved to the
Call Stack for execution.

In the diagram:

●​ Tasks like CB (e.g., setTimeout callbacks) are added


to the Task Queue and are only executed once the
Call Stack is cleared.

5. Event Loop
●​ The Event Loop is the mechanism that continuously
monitors the Call Stack and the Task Queues.
●​ It ensures smooth execution by:
○​ Checking if the Call Stack is empty.
○​ Prioritizing and executing tasks from the High
Priority Queue first.
○​ Then, processing tasks from the Task Queue.

IMPORTANT:

See this:
Asynchronous nature of
Javascript

●​ Since code inside red box is using setTimeout() , it is


asynchronous code.
●​ While normal [Link](“...”) are synchronous code.
●​ In javascript all synchronous code is executed first
and then after that asynchronous code is executed.
●​ During execution of synchronous code, javascript
skips all the asynchronous code coming in the path.
●​ Execution order of synchronous code: in top to
bottom direction one by one, one line at a time.
●​ Execution order of asynchronous code: determined
by the event loop, the task queue, and the microtask
queue.
For more details: click here.

See output:

Javascript Callbacks
Actually callback is nothing but calling a function inside
some other function and continuing this as per our
[Link] this we pass one function as the
parameter of some other function.
But if there are too many functions calling them inside
one another then the code will be very difficult to read
and manage. This causes a problem called “callback hell”.
This can be solved using promises.
Javascript Promises
●​ used to handle asynchronous operations or tasks.
But why not synchronous tasks: click here
●​ Since promise is an alternative (a better one) to
callback, the main purpose of promise is similar to
callback.
●​ Async task immediately execute nahi hota hai. Pahle
sare sync task execute ho jaate hain uske baad hi
async task ka execution start hota hai. Ab agar hame
koi sync task ya koi function kisi particular async task
ke baad hi execute karna hai to aisa hum kaise
karenge. Kyunki koi bhi sync task bhale hi wo async
task ke baad hi kyun na likha ho wo sync task async
task se pahle hi execute hoga. To aisa hum kya karen
ki jis bhi task ( sync, async, or function) ko hum jis
bhi kisi async task ke baad execute karana chhate
hain kara payen. Isi ke liye promise or callback ka use
kiya jata hai.
●​ So, in simple terms both are used to define what
should happen after an async task is done, whether it
succeeds or fails.
To see how using callback also we can define what to
do after task succeeds or what if it fails: click here.
And to see how using promise we can do so, see below:
●​ Yahan success or fail ka matlab task ke successfully
run hone ya phir kisi error jaise syntax error ke
karan task ke fail ho jane se nahi hai. Agar Syntax
error ya aisa koi other programmatical error hoga tab
to task obviously fail hoga.
●​ Yani yahan success ya fail se kisi programmatical
error se nahi hai balki promise ke respect me success
ya fail se hain. Matlab jis task ke saath resolve call
hoga wo promise ke liye success hoga. Aur task ke
saath reject call hoga wo promise ke liye fail hoga.
●​ Jis bhi async task ke saath hame upar mentioned
points jaisa karna hota hai uss task ko hum promise
object ke inside likhte hain. Phir uss task me ek saath
hum ya to resolve() call karte hain ya phir reject() call
karte hain. Ab agar resolve() call kiya to promise
fulfilled state attain kar lega yani promise will assume
that task has completed successfully. To promise ke
liye task ke success assume karne ke baad kya karna
hai, isko .then() ka use karke define kiya jayega.
To see how .then() will be used for above purpose: click here
Agar reject() call kiya to promise will attain rejected
state yani promise will assume that the task has
failed. Matalb although there may be no
programmatical error but reject() will generate an
error due to which promise will assume that the task
has failed. To promise ke task ko fail assume karne ke
baad kya karna hai( yani reject() se generated error
ko kaise handle karna hai), isko .catch() ka use karke
define kiya jayega.
●​ But a promise is much better than a callback.
To See: click here.

Three states of promise


To see those three states: click here

Why Promises Are Not for Synchronous Tasks:


1.​ No Time Taken for Synchronous Tasks:​
A synchronous task (e.g., simple math or printing to
the console) completes immediately. Wrapping such
tasks in a promise adds unnecessary overhead and
complexity.
2.​Promises Are Asynchronous by Design: Promises
always run their .then(), .catch(), and
.finally() callbacks after the current
synchronous code has finished executing. So, this is
waste of time & resources increasing complexity in
vain.
What Happens If You Use a Promise for a Synchronous
Task?

You can technically wrap a synchronous task inside a


promise, but it doesn't make sense because the task is
already completed by the time the promise resolves.

It means:

The distinction is not that synchronous tasks "definitely


execute" while asynchronous tasks "may or may not."
Instead:

●​ Synchronous tasks execute immediately as part of


the main program flow.
●​ Asynchronous tasks are delayed and depend on
external conditions to complete (e.g., network
stability or success of an operation).

Promises help you handle this uncertainty in asynchronous


tasks by allowing you to define what to do when they
succeed (.then()) or if they fail (.catch()).

Since there is certainty (immediate execution &


guaranteed completion) with synchronous tasks, so using
promises with synchronous tasks only adds complexity &
waste of time and resources.

That’s why promises are better to use with asynchronous


tasks & stupidity to use with synchronous tasks.
Clarification on what is Promise actually

Is promise an object or a class or a constructor or a


function? What is it actually?

1. Is Promise a Function?
●​ Yes, Promise is a function, specifically a constructor
function (type of function).
●​ In JavaScript, constructors are special functions
used to create and initialize objects.
●​ Promise is designed to create Promise objects.
For eg.,
[Link](typeof Promise); // output -> "function"

2. Is Promise a Constructor?

●​ Yes, Promise is a constructor because you use it


with the new keyword to create a new Promise
object.

Eg.,

3. Is Promise an Object?
●​ The Promise itself is not an object, but the result
of new Promise(...) is an object.
●​ This object is an instance of the Promise class, and
you use this object to handle asynchronous
operations.

4. Is Promise a Class?

●​ Technically, Promise is implemented as a class in


JavaScript.
●​ In ES6, classes are a syntactical sugar over
constructor functions. This means Promise behaves
like a class, but under the hood, it's still a
constructor function.

Summary:

●​ Promise is a constructor function.


●​ It can be considered a class since it follows ES6 class
behavior.
●​ So, Promise is a constructor function (which acts
as a class).
●​ You use new Promise(...) to create Promise
objects.
●​ The Promise object is what you interact with to
handle asynchronous tasks using .then(), .catch(),
and .finally().
For more details on above topic: click here

Creation of promises

Syntax to create a new promise object :


new Promise(function(resolve,reject) {​
// code for asynchronous task here.​
})

1.​ new Promise: this creates a new promise


object.
2.​ Executor Function:
●​ The Promise constructor takes a single
argument, which is a function (called the
executor function).
●​ function(resolve,reject): this is the
executor function.

3.​ Parameters of the Executor Function:


●​ The executor function has two functions as
Parameters:
●​ resolve: this is a function and it has been
passed as a parameter because we will need to
use it or call it inside our promise object. To see
why we will need to use it or call it inside our
promise object: click here
●​ reject: Similarly, for reject.

Now see:
Now consuming the promise:
If we don’t call resolve() inside promise object

Now see its output:

Now calling resolve() inside promise object:


Now see the output:

If we don’t call resolve() or reject() inside promise object,


the promise will remain in pending state, even if the task
has already completed and any .then() or .catch() or
await calls associated with it will never execute.
We will not be able to handle the asynchronous task
defined inside promise object. Even if that task may have
finished but since promise will assume that the task is
still pending (promise is in pending state) we are not able
to define what to do further if the task succeeds & what
if it fails using .then() or .catch().
Until promise knows that the task has either completed or
failed ( not in pending state), we can’t use .then() or
.catch() like functions to handle the task further. And
promise will know this only when either resolve() or
reject() is called inside it.
resolve()
●​ resolve() is a function provided by the Promise
constructor.
●​ It is passed as the parameter of executor function.
●​ If we want to make promise assume that the task has
completed successfully yani has resolved, we must
call resolve() inside promise object along with this
task. For better clarification: Click here.
●​ After that it sends a result (optional) to the
.then() function. Inside .then() it is mentioned that
what to do on successful completion of the task.
Parameters Passed to resolve()

See in output the value passed through resolve() got


printed due to the execution of .then() function:

1.​ Any Single Value: You can pass any data type as a
parameter to resolve():
○​ Primitive values (e.g., strings, numbers, booleans)
○​ Objects
○​ Arrays
○​ Functions
2.​Another Promise: If you pass another Promise to
resolve(), the current Promise will adopt the state
of the passed Promise. It will resolve or reject based
on that Promise.
3.​Nothing (Undefined): If no parameter is passed, the
resolved value will be undefined.

In the above example of “username” we have passed an


object ( a key-value pair) through resolve().

For examples & more about this: click here

reject()
●​ Like resolve(), reject() is also a function used in
promise constructor and passed as a parameter of
the executor function.
●​ When reject() is called, it always generates error
although there may be no programmatical or syntax
error.
Due to this error the promise gets the signal or
assumes that the task has failed.
●​ So, if we want to make promise assume that the task
has failed ( send promise from pending to rejected
state) we must call reject().
●​ Now what to do after promise assumed that the task
has failed is defined using .catch() functions or 2nd
parameter of .then().

Parameters passed to reject()


Same type of parameters that passed to resolve().
Now see use of .then() and .catch():

.then()

●​ Under resolve() & reject() section, we seen their


result yani what they do.
●​ To define what to do after these results, .then()
is used.

●​ To see more & examples : click here


.catch()
●​ It does not handle results of resolve(), only handles
the results of reject().
●​ So, under the section of reject(),we have seen the
result of reject() is the error and assumption of
promise that the task has failed.
●​ Now, what to do after these results is defined using
.catch().
●​ For more examples & points: click here

Handling errors in promise object


●​ .catch() or 2nd parameter of .then() is used to handle
errors generated due to execution of reject()

See the output:


Now handling the error generated due to execution of
reject() :

Now see the output without error:

Now, this time assigning “error” variable = false. So this


time if block will execute but else will not. So, resolve()
will execute not reject(). So, .then() will execute not
.catch() this time.
See:
See output:

Not storing the promise object in a variable


Now, see this time we didn’t store promise object in
variable like we did in above code ( storing in promiseOne):
Chaining in promise
See:

See we get errors in the output for the above code:

This way we can can’t print username. For this purpose we


need chaining in promises.
See output:

Use of .finally()

Executed in Both Cases: .finally() is executed


whether the promise is resolved or rejected.

Syntax:
●​ onFinally: A callback function that takes no
arguments. It is executed after the Promise is
resolved or rejected.

See eg.,

Output:

It’s not that you always handle promise with .then() &
.catch(). You can also handle it with async/await syntax.

Async/Await
async: Marks a function as asynchronous. It ensures the
function always returns a promise.
await: Pauses the execution of the async function until
the promise is resolved or rejected.
For more on async/await: click here
See:

See output:

Now to handle the error using try-catch block:


See output this time:

To See explanation of above code: click here.

fetch()
See:
Now using try catch but still something missing:

This time also will get no output as [Link]() is


taking time. For video part: click here
Now see the perfect code:

Output:
For video part of output : click here
For explanation of above code: click here

This time using .then() & .catch() with fetch() :

Output:
For video part: click here
For explanation of above code: click here

See more fetch() in depth:


Now see 2nd part of fetch() [green part] :

For video part of fetch() in depth: click here

You might also like