0% found this document useful (0 votes)
2 views55 pages

Javascript

JavaScript is a high-level, interpreted programming language primarily used for interactive web applications, running both in browsers and on servers. It includes various data types such as primitives (string, number, boolean, etc.) and objects, with specific variable declarations (const, let, var) and operators for manipulation. Key concepts include scope, closures, asynchronous execution, and DOM manipulation techniques for handling HTML elements.

Uploaded by

ayush.it222041
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)
2 views55 pages

Javascript

JavaScript is a high-level, interpreted programming language primarily used for interactive web applications, running both in browsers and on servers. It includes various data types such as primitives (string, number, boolean, etc.) and objects, with specific variable declarations (const, let, var) and operators for manipulation. Key concepts include scope, closures, asynchronous execution, and DOM manipulation techniques for handling HTML elements.

Uploaded by

ayush.it222041
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 → JavaScript is a high-level, interpreted, single-threaded

programming language mainly used to make web applications interactive.


It runs in the browser as well as on the server using [Link].

Variable in Javascript

1.​ Const → const declares a block-scoped variable with a constant reference.

2.​ Let → let declares a block-scoped variable that can be reassigned.

3.​ Var → var declares a function-scoped or globally-scoped variable that can be


reassigned and redeclared. Its use is discouraged in modern JavaScript (ES6+).

Data Types in Javascript

1. Primitive Types

Primitives are fundamental, immutable data types. "Immutable" means that their value
cannot be changed once created. Operations that appear to modify a primitive actually
create a new one. A variable holding a primitive stores the primitive's value directly.

There are seven primitive types:


string

●​ Purpose: Represents textual data.


●​ Syntax: A sequence of characters enclosed in single quotes ('...'), double quotes
("..."), or backticks (...).

number

●​ Purpose: Represents both integer and floating-point numbers.


●​ Syntax: A numeric literal. There is no distinction between int and float.
●​ Special Values: Includes Infinity, -Infinity, and NaN (Not a Number).

boolean

●​ Purpose: Represents a logical entity with two possible values.


●​ Syntax: The keywords true or false.

undefined

●​ Purpose: Represents the unintentional absence of a value. A variable that has been
declared but not assigned a value is automatically undefined.
null

●​ Purpose: Represents the intentional absence of any object value. It is a primitive


value that is explicitly assigned by a developer to indicate "no value."

null vs. undefined: undefined is the default when nothing is assigned. null is an
explicit assignment of "nothing."

bigInt

●​ Purpose: Represents whole numbers larger than the maximum safe integer value
●​ 3 of 19
●​
●​ that the number type can represent.
●​ Syntax: An integer literal followed by the n suffix.

symbol

●​ Purpose: Represents a unique, anonymous identifier. Symbols are primarily used as


unique property keys for objects to avoid naming collisions.
●​ Syntax: Created using the Symbol() factory function.

2. The Object Type (Non-Primitive)


An object is a mutable collection of key-value pairs (or properties). Unlike primitives,
variables assigned to an object do not store the object itself, but rather a reference (or a
pointer) to the object's location in memory.

●​ Object Literals: The most common way to create an object. code JavaScript

●​ Arrays: A specialized type of object used for ordered collections. code JavaScript

●​ Functions: In JavaScript, functions are also a special type of object. code JavaScript

Key Difference: Value vs. Reference

This is the most critical distinction between primitive and object types.

Primitives are Passed/Assigned by Value

When we assign a primitive from one variable to another, the value is copied.
Objects are Passed/Assigned by Reference

When we assign an object from one variable to another, the reference (memory address)
is copied, not the object itself. Both variables point to the same object.

The typeof Operator

To determine the data type of a variable at runtime, we use the typeof operator.
The Two Memory Regions in V8

When we JavaScript code runs, the V8 engine manages two primary areas of
memory:

1.​ The Call Stack: A highly organized region for managing function execution.
It's fast and stores fixed-size data. On a 32-bit system, the "slots" on the
stack are 32 bits (4 bytes) each.
2.​ The Heap: A large, less organized region for storing data that can change in
size or has a longer lifetime. This is where objects, arrays, and other complex
data live.
In JavaScript, an operator is a special symbol or keyword used to perform an
operation on values.

Assignment Operators: = (Assignment) The fundamental assignment operator. It


assigns the value on its right to the variable on its left. code JavaScript.

Arithmetic Operators

●​ (Addition)
●​ (Subtraction)
●​ (Multiplication)
●​ / (Division)
●​ (Exponentiation - ES2016): 2 ** 3 evaluates to 8.
●​ % (Remainder / Modulo): Returns the remainder of a division. This is
extremely useful for tasks like checking if a number is even or odd.
code JavaScript
●​ ++ (Increment) & -- (Decrement): Increases or decreases a number by
1. code JavaScript
○​ Gotcha: Prefix vs. Postfix. The position of the operator matters
critically.
○​ Postfix (variable++): The expression evaluates to the variable's
original value, and then the variable is incremented.
○​ Prefix (++variable): The variable is incremented first, and then
the expression evaluates to the new value.

Comparison Operators

These operators compare two values and evaluate to a boolean (true or false).

●​ (Greater than)
●​ < (Less than)
●​ = (Greater than or equal to)
●​ <= (Less than or equal to)
●​ == (Loose Equality)
●​ === (Strict Equality) {compare without auto converting}

Logical Operators

●​ && (Logical AND): Evaluates to true only if both operands are true (or
"truthy").
●​ || (Logical OR): Evaluates to true if either operand is true
●​ ! (Logical NOT): Inverts the boolean value of its operand. It coerces the
operand to a boolean first, then flips it

Conditional Loop:
Loops:

1.​ For Loop

[Link] Loop

3. Do-while Loop
[Link] →

Number:
Math Object:
String:
Date:
Array: Note

Object: An object is a collection of labeled data.

→ Accessing (Reading) Properties:


[Link] Notation:


[Link] Notation ([]): The more powerful and flexible way. The key
inside the brackets is a string.

CRITICAL USE CASE: Bracket notation allows us to use a variable


to determine which property to access.

→Updating and Adding (Creating), Delete Properties


Objects with Methods:

Looping Over an Object's Properties (Iteration)

A. The Loop For…in (The Old Way)


[Link] Modern Object Methods (The Better Way) These methods return
arrays, which we can then loop over with a for...of loop.

●​ [Link](obj): Returns an array of the object's own property


keys.
●​ [Link](obj): Returns an array of the object's own property
values.
●​ [Link](obj): Returns an array of [key, value] pairs.

How to Copy an Object (Shallow Copy)

⭐⭐⭐
Modern ES6+ Syntax (Syntactic Sugar)

[Link] Value Shorthand: If we have a variable with the same


name as a property key, we can just use the variable name once.

[Link] Shorthand : We can omit the function keyword when defining


methods.
Function:
A function is a reusable "code machine" or a "recipe."

A. Function Declaration

B. Function Expression
Arrow Functions (ES6 - The Modern Way)

Syntax Rules for Arrow Functions:


[Link] Return: If the function body is just a single expression, we can
remove the curly braces{} and the return keyword.

[Link] Parameter: If there is only one parameter, we can remove the


parentheses().

Advanced Parameter Concepts


A. Default Parameters (ES6):We can provide a default value for a
parameter in case it's not passed in (i.e., it's undefined).

B. Rest Parameters (...) (ES6): This allows a function to accept an


indefinite number of arguments and gather them into a true array.
Important Gotcha: Returning an Object Literal

CallBack Function→
​ A callback function in JavaScript is a function passed as an argument to
another function.

How Js Code Execute?


Hoisting is JavaScript's behavior of knowing about a variable or
function's existence before executing the code. How it treats that
knowledge depends on the keyword (function, var, let, or const).Arrow
function can’t Hoisted as it cannot be call before initization.

●​ function: Hoisted completely (name and body).


●​ var: Hoisted and initialized with undefined.
●​ let/const: Hoisted, but not initialized. They are put in a Temporal
Dead Zone.

Scope :The visibility and accessibility of variables. It answers: "From where


can I access this variable?"
Three Types of Scope:
[Link] Scope (The House Itself)

[Link] Scope (A Room)

[Link] Scope (A Closet in a Room)


Important: Var is NOT block-scoped, only function-scoped!

Lexical scope → Scope is determined by where we write the code, not


where we call it.
Closure : A function that remembers variables from its outer scope even
after the outer function has finished executing.

Importance:

Without closures: Functions would only access their own variables and globals.

With closures: Functions can "carry" their environment with them!

What just happened?

1.​ outer() runs and creates message


2.​ inner() is defined INSIDE outer() - it "closes over" message
3.​ outer() returns inner and finishes
4.​ Normally, message would be garbage collected... BUT
5.​ inner still has a reference to message - this is a closure!
6.​ When we call myFunction() (which is inner), it still remembers message
A higher-order function is a function that either:

1.​ Takes a function as an argument, OR


2.​ Returns a function as a result
Important for Interviews:
1️⃣ JavaScript Nature​
JavaScript is single-threaded and runs code synchronously by default.​
It can still perform asynchronous operations using the event loop.

2️⃣ Synchronous Execution​


Tasks run one after another, and each step waits for the previous one to
finish.​
Long operations block the main thread and stop other code from running.

3️⃣ Asynchronous Execution​


Time-consuming tasks run in the background without blocking the main
thread.​
Used for operations like API calls, timers, and database/file handling.

4️⃣ CPU-Bound Tasks​


These involve heavy computation like loops, processing, or encryption.​
They run synchronously in JS and can freeze the app if not offloaded.

5️⃣ I/O-Bound Tasks​


These spend most of their time waiting on external systems like APIs or
databases.​
JavaScript handles them asynchronously so the event loop stays free.

Practice Set - 1

#Map() →
To create a new array by transforming every element from an original array.

●​ Key Characteristics:
○​ It always returns a new array.
○​ The new array will always have the same length as the original
array.
○​ It is non-mutating; it does not change the original array.
#Filter() →
To create a new array containing only the elements from the original array that
meet a specific condition.

●​ Key Characteristics:
○​ It always returns a new array.
○​ The new array can have the same length or be shorter than the
original. It will never be longer.
○​ It is non-mutating.

*map() transforms every element of an array, returning a new array with


the modified values, whereas filter() selects elements that satisfy a
condition, returning a new array with only those elements.*

#reduce() →
To execute a "reducer" function on each element of the array, resulting in a
single output value.

●​ Key Characteristics:
○​ It is the most powerful and flexible of the iteration methods.
○​ It can return any type of value: a number, a string, an object,
another array.
○​ It is non-mutating.
●​ accumulator acts as storage of the ongoing result.
●​ currentValue is the current element that is being processed in the
loop.
#find() →
Like filter() but it stops and returns the very first element that matches the
condition. If nothing matches, it returns undefined.

#some() →
Checks if at least one element in the array passes the test. Returns true or
false. It stops as soon as it finds one.

#every() →
Checks if all elements in the array pass the test. Returns true or false. It
stops as soon as it finds one that doesn't pass.

#Set → A Set in JavaScript is a collection of unique values, meaning no duplicates are


allowed.
#Map Object→ A JavaScript Map is an object that can store collections of
key-value pairs,
#DOM→ "The DOM (Document Object Model) is a tree-like representation of our
HTML document that JavaScript can understand and manipulate.
Key Concepts:
1. Everything is a Node →
Types of Nodes: -
Element Nodes: <div>, <p>, <h1> -
​ Text Nodes: The actual text content -
Document Node: The root (document)

2. HTML Elements Become Objects

3.. The window and document Objects →


●​ window = The browser environment (has alert, setTimeout, localStorage,
etc.)
●​ document = Our HTML page (the DOM tree)
Selecting Elements:

Manipulating Elements:

1. innerHTML returns or sets the HTML content inside an element.

Key Points:

●​ Includes HTML tags


●​ Does not consider CSS visibility
●​ Can be used to insert HTML elements
●​ Security risk if used with user input (XSS)
2. innerText returns only the visible text as shown on the screen.

Key Points:

●​ Ignores HTML tags


●​ Respects CSS styling (hidden elements not included)
●​ Slower because it considers layout (reflow)

[Link] returns all text inside an element, including hidden text.

Key Points:

●​ Ignores HTML tags


●​ Does not consider CSS visibility
●​ Faster than innerText
●​ Safest way to insert text
#CRUD Operations:

1. Creating a New Element: [Link]()

[Link] Common Attributes (Direct Properties)

[Link] CSS Classes (The .classList Toolbox)

This is the best and safest way to manage an element's classes. Forget about
.className.

●​ .add('className'): Adds a new class.


●​ .remove('className'): Removes a class.
●​ .toggle('className'): Adds the class if it's missing, removes it if it's there.
●​ .contains('className'): Checks if an element has a class (returns true
or false).

4. Changing Inline Styles

[Link] Inside a Parent (as a Child)

[Link](...nodes) (Modern & Recommended)

●​ What it does: Inserts the node as the very last child of the parent.
●​ Use Case: The default way to add an item to the end of a list or container.

[Link](...nodes) (Modern & Recommended)

●​ What it does: Inserts the node as the very first child of the parent.
●​ Use Case: Adding a new item to the top of a feed or a list.
[Link] Next to an Element (as a Sibling)

[Link](...nodes) (Modern & Recommended)

●​ What it does: Inserts the node immediately after the reference element, as its next
sibling.
●​ Use Case: Adding a new element directly following another one.

[Link](...nodes) (Modern & Recommended)

●​ What it does: Inserts the node immediately before the reference element, as its
previous sibling.
●​ Use Case: Adding a new element directly preceding another one.

[Link] an Element
📌 DocumentFragment (DOM)
DocumentFragment is a lightweight container used to store DOM nodes temporarily
before inserting them into the actual DOM.

It is not part of the live DOM, so changes made inside it do not trigger reflow/repaint.

Why use DocumentFragment?

●​ 🚀 Better performance​
●​ 🧠 Avoids multiple DOM re-renders​

●​ 💯 Best for adding many elements at once


✅ What happens?
1.​ <li> elements are created in memory
2.​ Appended to DocumentFragment
3.​ Fragment is appended once to DOM
4.​ Faster + cleaner

Important Points (Interview 🔥)


●​ DocumentFragment disappears after append
●​ Nodes move into DOM, fragment becomes empty
●​ Not visible in HTML tree
●​ Can hold multiple nodes

When to Use

✔ Rendering lists​
✔ Table rows​
✔ Dropdown options​
✔ Large DOM updates

📌 addEventListener() (DOM Events) ⭐


addEventListener() is used to attach an event handler to a DOM element so it can
respond to user actions like click, keypress, submit, hover, etc.

Common Event Types to Know

●​ Mouse Events:
○​ click: A single click.
○​ dblclick: A double click.
○​ mousedown: When the mouse button is pressed down.
○​ mouseup: When the mouse button is released.
○​ mouseover: When the mouse pointer enters an element.
○​ mouseout: When the mouse pointer leaves an element.
○​ mousemove: Fires continuously as the mouse moves over an element.
●​ Keyboard Events:
○​ keydown: When a key is pressed down.
○​ keyup: When a key is released.
○​ keypress: (Older, avoid) Fires when a key that produces a character is
pressed.
●​ Form Events:
○​ submit: When a form is submitted.
○​ input: Fires immediately when the value of an <input>, <select>, or
<textarea> changes.
○​ change: Fires when the value changes and the element loses focus.
●​ Window Events:
○​ load: Fires when the entire page (including images, scripts, etc.) has
finished loading.
○​ DOMContentLoaded: Fires when the HTML document has been fully
parsed and the DOM tree is ready (this is often a better choice than load
as it fires earlier).
○​ scroll: Fires when the user scrolls the document.

📌 Event Capturing & Event Bubbling (DOM Events)

These are two phases of event propagation in the DOM.

When an event happens, it travels in three phases:

Capturing → Target → Bubbling

1️⃣ Capturing Phase (Trickling Down)

Event goes from outer → inner element


Parent → Child

2️⃣ Target Phase 🎯

3️⃣ Bubbling Phase (Default)


Event goes from inner → outer element

Child → Parent

“Event capturing moves from parent to child, while event bubbling moves from child
to parent; bubbling is the default and widely used in event delegation.”
#Event Object (event / e)
When an event occurs and our handler function is called, the browser automatically
passes a special object as the first argument to our function. This is the event object.
"The event object is an information packet that tells me everything about what just
happened."

🔹 Commonly Used Event Object Properties (🔥


Interview)

1️⃣ [Link]

👉 Element where the event originated


[Link]([Link]);

2️⃣ [Link]

👉 Element on which listener is attached


[Link]([Link]);

3️⃣ [Link]

👉 Type of event
[Link]([Link]); // click, submit, keydown

4️⃣ [Link]()

👉 Stops default browser behavior


[Link]("submit", (e) => {
[Link](); // stops page reload
});
5️⃣ [Link]()

👉 Stops bubbling / capturing


[Link]();

6️⃣ [Link]

👉 Checks if event bubbles or not


[Link]([Link]); // true / false

Event Delegation Using Event Object:

Event Loop (JavaScript)

The Event Loop is what allows JavaScript (single-threaded 🔹) to handle asynchronous


operations like timers, promises, DOM events, API calls, etc.

🧠 Why Event Loop is Needed


●​ JS runs one task at a time
●​ But browser can handle async work in background
●​ Event Loop decides what runs next

🔁 Main Parts of Event Loop


1️⃣ Call Stack

●​ Executes JS code
●​ LIFO (Last In, First Out)

2️⃣ Web APIs

●​ Browser features​
(setTimeout, DOM events, fetch, etc.)

3️⃣ Task Queue (Callback Queue / Macrotask Queue)

●​ setTimeout
●​ setInterval
●​ DOM events

4️⃣ Microtask Queue

●​ [Link]()
●​ catch()
●​ finally()
●​ queueMicrotask()

👉 Microtasks have higher priority


🔄 How Event Loop Works (Step-by-Step)

1.​ JS code goes to Call Stack


2.​ Async code is sent to Web APIs
3.​ When async task finishes:
○​ Callback → Task Queue / Microtask Queue
4.​ Event Loop checks:
○​ Is Call Stack empty?
○​ First executes Microtasks
○​ Then Macrotasks
Callback Hell happens when callbacks are nested inside callbacks, making code hard to
read, debug, and [Link] is solved using Promises or async/await.

📌 Promises :

A Promise is an object that represents the eventual completion or failure of an


asynchronous operation.

Promise Characteristics:

1.​ A Promise is an object - we can store it in a variable


2.​ Represents future value - The value isn't available yet, but will be
3.​ Has states - It changes state over time
4.​ One-time use - Once settled, it never changes

👉 A Promise says:
“Do all the work in the background. When the result is ready, I will appear (resolve or
reject).”

Promise States (First Principles)


A Promise can be in exactly ONE of three states at any time:

PROMISE STATES
1. PENDING (Initial state)

"I'm working on it..."

├── Success → 2. FULFILLED (Resolved)

│ "I got the result!"

└── Failure → 3. REJECTED

"Something went wrong!"

Once FULFILLED or REJECTED, the promise is SETTLED (final)

👉 “A Promise is fulfilled when the server responds, regardless of HTTP status. It is


rejected only when the request fails completely, like network issues or timeout.”
Promise Chaining ( 🔥 Important)

JSON vs JavaScript Object


Converting Between JSON and JavaScript Objects

[Link] Object → JSON String

[Link] String → JavaScript Object


Q. Why Does fetch() Return JSON?

The flow:

1.​ Server sends data as JSON string (text)


2.​ fetch() receives it as a Response object
3.​ .json() parses the JSON string → JavaScript object
4.​ Now you can use it like a normal JS object

#Async Await → async and await are used to handle asynchronous operations (such
as API calls, file reading, database queries) in a cleaner way than Promises.

Interview Points

1.​ async makes a function return a Promise.


2.​ await can only be used inside an async function.
3.​ await pauses execution of the current async function, not the entire program.
4.​ async/await is syntactic sugar over Promises.
5.​ Use try...catch for error handling.
#Execution Flow

#Async/Await Execution Steps

#Step-by-Step Execution

Step 1: Promise Creation

●​ A Promise p is created.
●​ setTimeout() starts a timer for 10 seconds.
●​ Promise state = Pending.

Step 2: handlePromise() is Called

handlePromise();

●​ Function is pushed onto the Call Stack.

Step 3: First Console Statement Executes

[Link]("Hello World!!");

Output:

Hello World!!

Step 4: Execution Reaches await

const val = await p;

●​ Promise p is still pending.


●​ handlePromise() execution is paused.
●​ The remaining code after await is suspended.
●​ Control is returned to the JavaScript Engine.

Important: JavaScript Engine is NOT blocked.

Step 5: Waiting Period

●​ For 10 seconds, JavaScript can execute:


○​ Other functions
○​ Event handlers
○​ Timers
○​ API callbacks

Step 6: Promise Resolves

resolve("Promise Resolved Value!!");

After 10 seconds:
●​ Promise state changes:
○​ Pending → Fulfilled
●​ Value = "Promise Resolved Value!!"

Step 7: Resume Async Function

●​ The remaining part of handlePromise() is placed in the Microtask Queue.


●​ Event Loop moves it to the Call Stack when the stack becomes empty.

Step 8: Remaining Code Executes

[Link]("Namaste JavaScript");

[Link](val);

Output:

Namaste JavaScript

Promise Resolved Value!!

Final Output

Hello World!!

(10 second delay)

Namaste JavaScript

Promise Resolved Value!!


#Rule

Always wrap await statements that may fail (API calls, database calls, file
operations, etc.) inside a try...catch block to handle Promise rejections
gracefully.

You might also like