Javascript Guide
Javascript Guide
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:
Javascript Variables
Rules for choosing variable names in Java script:
But, also objects are more than just being traditional key-value pairs.
See:
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:
Output:
● This semicolon at the end of line is optional in
javascript.
Operators in js
Output:
Javascript functions
These are similar to c++ functions.
For more: click
Arrow function
Syntax:
Example Comparison
Again see the comparison:
Summary:
One more thing to notice :
In javascript functions
”
“ this in javascript
Javascript strings
Click here
Javascript arrays
output:
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:
[Link]
Document Object Model
Tree Structure
DOM Selectors
Various methods/functions of the document object in JS:
getElementById
Syntax: getElementById(‘idName’)
getAttribute
setAttribute
Inserting style using DOM
textContent
To extract content or values from an element:
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:
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:
Syntax:
Output:
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 more:
Also see:
See output:
Applying “for” loop on the HTMLCollection obtained from
[Link]. See:
See output:
2.lastElementChild
Output:
Gives last child(element) of the element selected by
querySelector(.parent) which is referred by parent object.
3.parentElement
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:
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:
createTextNode()
● used to create a text node, which represents a string
of text to be added to an HTML document.
Syntax:
createTextNode():
innerText:
● Can be slower because it involves more processing
(e.g., layout recalculations if styles like display:
none affect visibility).
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.
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.
replaceWith()
For more with replaceWith(): click
Using addEventListener()
This is the best method.
Event Propagation
See the output in console:
To stop bubbling:
stopPropagation()
See result:
preventDefault()
removeChild()
[Link](removeIt):
Use of tagName
Javascript is:
● Synchronous
● Single threaded
Blocking Code
● Blocks the flow of program
● Read file sync
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.
In the diagram:
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
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.
It means:
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?
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?
Summary:
Creation of promises
Now see:
Now consuming the promise:
If we don’t call resolve() inside promise object
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.
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().
.then()
Use of .finally()
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:
fetch()
See:
Now using try catch but still something missing:
Output:
For video part of output : click here
For explanation of above code: click here
Output:
For video part: click here
For explanation of above code: click here