Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
JavaScript – Introduction
✅ WHAT is JavaScript?
JavaScript is a programming language and a scripting language used to make web
pages interactive and dynamic. Also used in backend to process the action.
In simple words:
JavaScript gives life to a website.
Without JavaScript:
Website is static
Only text and images
No interaction
With JavaScript:
Button clicks work
Form validation
Popups & alerts
Dynamic content updates
Example:
<button Me</button>
👉 Clicking the button shows a message — this is JavaScript in action.
✅ WHY JavaScript is used?
1️⃣ To make websites interactive
Examples:
Login validation
Dropdown menus
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
Image sliders
Modal popups
2️⃣ To improve user experience
No page reload
Faster response
Smooth animations
3️⃣ To build complete applications
Using JavaScript you can build:
Websites
Web apps
Mobile apps
Backend servers
Interview Line (Important ⭐):
JavaScript is used to create interactive, dynamic, and responsive web applications.
✅ HOW JavaScript works?
Step-by-step flow:
1. Browser loads HTML
2. Browser loads CSS
3. Browser executes JavaScript line by line
JavaScript runs inside:
👉 JavaScript Engine
Chrome → V8
Firefox → SpiderMonkey
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
How JS is executed?
JS is single-threaded
Executes one task at a time
Follows event-driven model
Example:
[Link]("Start");
[Link]("End");
✅ WHERE JavaScript is used?
1️⃣ Inside Browser (Client-side)
Examples:
Form validation
DOM manipulation
Event handling
[Link]("btn"). {
alert("Clicked");
};
2️⃣ Outside Browser (Server-side)
Using [Link]
APIs
Backend logic
Database operations
3️⃣ Real-world usage
Gmail
YouTube
Instagram
Netflix
WhatsApp Web
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
✅ WHEN JavaScript is executed?
JavaScript executes when:
Page loads
User clicks a button
User types in input
Data is fetched from server
Timer runs
Example:
setTimeout(() => {
[Link]("Executed after 2 seconds");
}, 2000);
✅ WHAT JavaScript can do?
✔ Change HTML content
✔ Change CSS styles
✔ Handle events
✔ Validate forms
✔ Communicate with servers
✔ Store data in browser
❌ WHAT JavaScript cannot do (Interview Question)
❌ Directly access files on user system
❌ Control browser settings
❌ Access OS hardware (without permission)
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
✅ How to add JavaScript to HTML?
1️⃣ Inline
<button >
2️⃣ Internal
<script>
alert("Hello");
</script>
3️⃣ External (Best Practice ⭐)
<script src="[Link]"></script>
🧠 Real-life analogy (Easy to remember)
HTML → Skeleton 🦴
CSS → Clothes 👕
JavaScript → Brain 🦴 (controls actions)
🎯 Interview-ready one-liner
JavaScript is a lightweight, interpreted, object-based scripting language used to create
interactive web pages.
JavaScript Engine
✅ What is a JavaScript Engine?
A JavaScript Engine is a program inside the browser (or [Link]) that reads,
understands, and executes JavaScript code.
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
👉 Browsers cannot understand JavaScript directly.
👉 The JS Engine makes it possible.
Simple definition (Interview-ready ⭐):
A JavaScript engine is a program that converts JavaScript code into machine code and
executes it.
✅ Why do we need a JS Engine?
Computers understand only:
Machine code (0s and 1s)
JavaScript is human-readable, so:
JS Engine acts as a translator
Converts JS → Machine code
Executes it step by step
✅ Where is JavaScript Engine used?
In Browsers:
Browser JS Engine
Chrome V8
Edge V8
Firefox SpiderMonkey
Safari JavaScriptCore
Outside Browser:
[Link] uses V8
So JavaScript runs on server also
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
✅ How JavaScript Engine works (Step-by-step)
Let’s take this code:
let x = 10;
[Link](x);
Step 1: Parsing
JS Engine reads the code
Checks syntax
Converts code into AST (Abstract Syntax Tree)
❌ Syntax error → execution stops
Step 2: Compilation
Modern engines use Just-In-Time (JIT) compilation
Converts JS into optimized machine code
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
Step 3: Execution
Executes code line by line
Manages memory
Handles function calls
✅ Important Parts of JavaScript Engine
1️⃣ Call Stack
Keeps track of function calls
Executes one function at a time
Example:
function a() {
b();
}
function b() {
[Link]("Hello");
}
a();
Call Stack flow:
a()
→ b()
→ [Link]()
2️⃣ Heap (Memory)
Stores objects and variables
Dynamic memory allocation
let obj = { name: "Raj" };
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
✅ Is JavaScript Interpreted or Compiled?
Interview trick question 😄
✔ Old JS → Interpreted
✔ Modern JS → JIT compiled
Best answer:
JavaScript is a dynamically typed language that uses JIT compilation.
✅ JS Engine & Single Thread
JavaScript engine is single-threaded
One call stack
One task at a time
❓ Then how async works?
👉 Browser APIs + Event Loop (next topic 🔥)
✅ JavaScript Engine vs Browser
JavaScript Engine Browser
Executes JS Provides UI
Call stack, heap DOM, Web APIs
Cannot access DOM Controls DOM
👉 JS Engine alone cannot manipulate DOM
🧠 Real-life analogy (Easy to remember)
JavaScript code → English sentence
JS Engine → Translator
Machine code → Computer language
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🎯 Interview one-liners (Save these ⭐)
JavaScript engine executes JavaScript code.
V8 is the JS engine used by Chrome and [Link].
JS engine uses call stack and heap.
JavaScript is single-threaded.
Variables in JavaScript
✅ What is a Variable?
A variable is a container used to store data values so that we can use, update, and
manipulate them later.
Simple definition:A variable is a named storage location for data in memory.
Real-life example
Think of a variable like a labeled box:
Label → variable name
Box content → value
✅ Why do we need Variables?
Without variables:
[Link](10 + 20);
With variables:
let a = 10;
let b = 20;
[Link](a + b);
✔ Code becomes readable
✔ Values can be reused
✔ Easy to update
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
✅ How to declare Variables in JavaScript?
JavaScript provides 3 keywords:
1. var (old)
2. let (modern)
3. const (modern)
1️⃣ var (Avoid using ❌)
Syntax:
var x = 10;
Problems with var:
Function scoped (not block scoped)
Can be redeclared
Causes bugs
Example:
var a = 10;
var a = 20; // allowed ❌
[Link](a); // 20
👉 This behavior creates confusion.
2️⃣ let (Recommended ✅)
Syntax:
let age = 25;
Features:
Block scoped { }
Cannot redeclare
Can reassign
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
Example:
let x = 10;
x = 20; // allowed
// let x = 30; ❌ error
Block scope example:
if (true) {
let y = 50;
}
// [Link](y); ❌ error
3️⃣ const (Best practice ✅)
Syntax:
const pi = 3.14;
Features:
Block scoped
Cannot redeclare
Cannot reassign
Example:
const country = "India";
// country = "USA"; ❌ error
Important interview point ⭐
For objects and arrays:
const user = { name: "Raj" };
[Link] = "Naga"; // allowed ✅
👉 You can modify content, but not reassign the variable.
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
✅ Difference between var, let, and const (Interview
Favorite)
Feature var let const
Scope Function Block Block
Redeclare Yes No No
Reassign Yes Yes No
Hoisting Yes (undefined) Yes (TDZ) Yes (TDZ)
✅ Variable Naming Rules
✔ Can contain letters, numbers, _, $
✔ Must start with letter, _, or $
❌ Cannot start with number
❌ Cannot use keywords
Valid:
let userName;
let _age;
let $price;
Invalid:
let 1name; ❌
let let; ❌
🎯 Interview one-liner
Variables are used to store data values in memory and JavaScript provides var, let, and const
to declare them.
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
Data Types in JavaScript
✅ What is a Data Type?
A data type defines what kind of value a variable can store.
👉 It tells JavaScript:
What the value is
What operations can be performed on it
Simple definition:
Data type specifies the type of data stored in a variable.
✅ Why Data Types are important?
To perform correct operations
To avoid unexpected bugs
For memory management
For decision making in programs
Example:
let a = 10; // number
let b = "10"; // string
Even though values look same, behavior is different.
✅ JavaScript is Dynamically Typed ⭐
This is very important for interviews.
👉 You don’t declare data types explicitly.
Example:
let x = 10;
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
x = "Hello";
x = true;
Same variable → different data types at runtime.
✅ Types of Data Types in JavaScript
JavaScript has two main categories:
1. Primitive (Simple)
2. Non-Primitive (Reference)
1️⃣ Primitive Data Types
Primitive types store single values and are immutable.
1. Number
Used to store numeric values.
let age = 25;
let price = 99.99;
✔ Integers
✔ Decimals
✔ Positive / Negative
Special values:
Infinity
-Infinity
NaN
2. String
Used to store text. Represents sequence of characters enclosed within quotes (“ ” , ‘ ’ ,` `)
let name = "Raj";
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
let msg = 'Hello';
let text = `Hi ${name}`;
3. Boolean
Stores only true or false.
let isLoggedIn = true;
let isAdmin = false;
Used in conditions.
4. Undefined
A variable declared but not assigned a value.
let x;
[Link](x); // undefined
5. Null
Represents intentional absence of value.
let data = null;
Interview trap ⚠️
typeof null // "object" (JS bug)
6. BigInt
Used to store very large numbers.
let big = 12345678901234567890n;
7. Symbol
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
Used to create unique identifiers.
let id = Symbol("id");
Mostly used in advanced JS.
2️⃣ Non-Primitive Data Types (Reference
Types)
They store multiple values and are stored by reference.
1. Object
Stores data in key-value pairs.
let user = {
name: "Raj",
age: 25
};
2. Array
Stores multiple values in order.
let colors = ["red", "green", "blue"];
3. Function
A block of reusable code.
function greet() {
[Link]("Hello");
}
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
✅ Difference: Primitive vs Non-Primitive (Very
Important)
Feature Primitive Non-Primitive
Stores Single value Multiple values
Stored as Value Reference
Mutable No Yes
Example number, string object, array
✅ typeof operator
Used to check data type.
typeof 10 // number
typeof "Hi" // string
typeof true // boolean
typeof undefined // undefined
typeof null // object ❌
typeof {} // object
typeof [] // object
typeof function(){} // function
🧠 Real-life analogy
Primitive → Photocopy 📄
Non-primitive → Original document 📂
🎯 Interview one-liners ⭐
JavaScript is dynamically typed.
Primitive data types are immutable.
Objects are stored by reference.
typeof null is a known JavaScript bug.
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
Operators in JavaScript
✅ What is an Operator?
An operator is a symbol that performs an operation on one or more operands
(values/variables).
Simple definition:
Operators are used to perform operations on values.
Example:
let sum = 10 + 5;
+ → operator
10 "5" → operands
✅ Types of Operators in JavaScript
JavaScript has many operators, but interviews mainly focus on these:
1. Arithmetic
2. Assignment
3. Comparison
4. Logical
5. Unary
6. Ternary
7. String
8. Type
9. Bitwise (basic idea)
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
1️⃣ Arithmetic Operators
Used for mathematical calculations.
Operator Meaning Example
+ Addition 10 + 5
- Subtraction 10 - 5
* Multiplication 10 * 5
/ Division 10 / 2
% Modulus (remainder) 10 % 3
** Power 2 ** 3
let a = 10;
let b = 3;
[Link](a % b); // 1
2️⃣ Assignment Operators
Used to assign values.
Operator Example Same as
= x = 10
+= x += 5 x = x + 5
-= x -= 2 x = x - 2
*= x *= 2 x = x * 2
/= x /= 2 x = x / 2
let x = 10;
x += 5;
[Link](x); // 15
3️⃣ Comparison Operators (Interview
Favorite ⭐)
Used to compare values → returns true/false.
Operator Meaning
== Equal (value only)
=== Strict equal (value + type)
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
Operator Meaning
!= Not equal
!== Strict not equal
> Greater than
< Less than
>= Greater or equal
<= Less or equal
10 == "10"; // true ❌
10 === "10"; // false ✅
Interview Tip ⭐
👉 Always prefer === over ==.
4️⃣ Logical Operators
Used in conditions.
Operator Meaning
&& AND
|| OR
! NOT
let age = 20;
let hasID = true;
if (age >= 18 && hasID) {
[Link]("Allowed");
}
5️⃣ Unary Operators
Work on single operand.
Operator Example
++ x++
-- x--
typeof typeof x
! !true
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
Operator Example
X+ coverts x to
+
number type
x- converts x to
- number type and
negetes
let i = 1;
i++;
[Link](i); // 2
6️⃣ Ternary Operator (Very Important ⭐)
Short form of if-else.
Syntax:
condition ? trueValue : falseValue;
Example:
let result = age >= 18 ? "Adult" : "Minor";
7️⃣ String Operators
+ is used for string concatenation.
let first = "Hello";
let last = "World";
[Link](first + " " + last);
8️⃣ Type Operators
Operator Use
typeof Check data type
instanceof Check object type
typeof 10; // number
[] instanceof Array; // true
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
9️⃣ Bitwise Operators (Basic idea)
Used at binary level.
Operator Name
& AND
` `
^ XOR
<< Left shift
👉 Usually not asked deeply for freshers.
🧠 Operator Precedence (Interview Trap ⚠️)
[Link](10 + 5 * 2); // 20
👉 * runs before +.
🎯 Interview One-liners ⭐
Operators perform operations on values.
=== checks value and type.
Ternary operator is shorthand for if-else.
Logical operators return boolean values.
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
Type Conversion in Javascript
✅ What is Type Conversion?
Type Conversion is a general term meaning:
Changing one data type into another datatype.
It can be:
Explicit (Type Casting)
Implicit (Type coercion)
Type Casting (Explicit Type Conversion)
✅ What is Type Casting?
In JavaScript, Type Casting = Explicit Type Conversion
👉 You manually convert the data type.
Example:
Number("10"); // 10
String(100); // "100"
Boolean(1); // true
✔ You control it
✔ Predictable
✔ Recommended
✅ Common Explicit Conversion Methods
String → Number
Number("10"); // 10
parseInt("10px"); // 10
parseFloat("10.5"); // 10.5
And also possible through + and – operators also
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
Let x=”10”;
[Link](x+) //10
[Link](x-) //-10
Number → String
String(100); // "100"
(100).toString(); // "100"
Any → Boolean
Boolean(0); // false
Boolean("Hi"); // true
Type Coercion (Implicit Type Conversion)
✅ What is Type Coercion?
Type Coercion means:
JavaScript automatically converts data types during operations.
👉 You did NOT ask JS to convert
👉 JS does it behind the scenes
🔥 Examples of Type Coercion (Very Important)
String + Number
"10" + 5; // "105"
👉 JS converts 5 → "5"
👉 Performs string concatenation
String - Number
"10" - 5; // 5
👉 JS converts "10" → 10
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
Boolean Coercion
if ("hello") {
[Link]("true");
}
👉 "hello" → true
Equality Coercion
10 == "10"; // true ❌
10 === "10"; // false ✅
Implicit vs Explicit Conversion (Key
Interview Table ⭐)
Feature Explicit Implicit
Who converts Developer JavaScript
Control Full No
Predictable Yes Sometimes confusing
Example Number("10") "10" + 5
Falsy Values (Coercion Rule – MUST
REMEMBER ⭐)
These values become false in boolean context:
false
0
""
null
undefined
NaN
Everything else → true
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
Common Interview Traps ⚠️
Number(null); // 0
Number(undefined); // NaN
Boolean(" "); // true
typeof NaN; // "number"
[] == false; // true (coercion)
Which one should YOU use?
✅ Prefer Explicit Conversion
❌ Avoid relying on Implicit Coercion
Best practice:
const age = Number(inputValue);
Interview One-Liners (Save These ⭐)
Type conversion means changing data type.
Type casting is explicit conversion.
Type coercion is implicit conversion.
=== avoids type coercion.
JavaScript is dynamically typed.
🔚 Final Mental Model (Easy to remember)
Explicit → I convert
Implicit → JS converts
Type casting → Explicit
Type coercion → Implicit
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
CONDITIONAL STATEMENTS
✅ What is a Conditional Statement?
A conditional statement is used to execute different blocks of code based on conditions.
👉 Condition always returns true or false.
✅ CONDITIONAL STATEMENTS IN
JAVASCRIPT
1️⃣ if Statement
🔹 Definition
The if statement executes a block of code only when the condition is true.
🔹 Syntax
if (condition) {
// code
}
🔹 Example
let age = 20;
if (age >= 18) {
[Link]("Eligible to vote");
}
2️⃣ if...else Statement
🔹 Definition
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
The if...else statement executes one block if the condition is true, otherwise another
block.
🔹 Syntax
if (condition) {
// true block
} else {
// false block
}
🔹 Example
let marks = 40;
if (marks >= 50) {
[Link]("Pass");
} else {
[Link]("Fail");
}
3️⃣ if …else if…else Statement
🔹 Definition
else if is used to check multiple conditions sequentially.
🔹 Syntax
if (condition1) {
// block 1
} else if (condition2) {
// block 2
} else {
// default
}
🔹 Example
let score = 85;
if (score >= 90) {
[Link]("Grade A");
} else if (score >= 75) {
[Link]("Grade B");
} else {
[Link]("Grade C");
}
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
4️⃣ switch Statement
🔹 Definition
The switch statement selects a block of code to execute based on a matched value.
🔹 Syntax
switch(expression) {
case value1:
break;
case value2:
break;
default:
}
🔹 Example
let day = 2;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
default:
[Link]("Invalid day");
}
5️⃣ Ternary Operator
🔹 Definition
The ternary operator is a short form of if-else used for simple conditions.
🔹 Syntax
condition ? expression1 : expression2;
🔹 Example
let result = age >= 18 ? "Adult" : "Minor";
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🔁 LOOPING STATEMENTS IN
JAVASCRIPT
✅ What is a Loop?
A loop is used to repeat a block of code until a condition becomes false.
1. for Loop
🔹 Definition
The for loop is used when the number of iterations is known in advance.
🔹 Syntax
for (initialization; condition; increment) {
// code
}
🔹 Example
for (let i = 1; i <= 5; i++) {
[Link](i);
}
Flow:
1. Initialize
2. Check condition
3. Execute block
4. Increment
5. Repeat
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
[Link] Loop
🔹 Definition
The while loop executes a block of code as long as the condition is true.
🔹 Syntax
while (condition) {
// code
}
🔹 Example
let i = 1;
while (i <= 3) {
[Link](i);
i++;
}
3. do...while Loop
🔹 Definition
The do...while loop executes the code at least once, even if the condition is false.
🔹 Syntax
do {
// code
} while (condition);
🔹 Example
let i = 5;
do {
[Link](i);
i++;
} while (i < 3);
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
[Link]...of Loop
🔹 Definition
The for...of loop is used to iterate over values of iterable objects like arrays.
🔹 Syntax
for (let value of iterable) {
// code
}
🔹 Example
let colors = ["red", "green", "blue"];
for (let color of colors) {
[Link](color);
}
5. for...in Loop
🔹 Definition
The for...in loop is used to iterate over keys of an object.
🔹 Syntax
for (let key in object) {
// code
}
🔹 Example
let user = { name: "Raj", age: 25 };
for (let key in user) {
[Link](key, user[key]);
}
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
break Statement
🔹 Definition
The break statement terminates the loop or switch immediately.
🔹 Example
for (let i = 1; i <= 5; i++) {
if (i === 3) break;
[Link](i);
}
continue Statement
🔹 Definition
The continue statement skips the current iteration and moves to the next one.
🔹 Example
for (let i = 1; i <= 5; i++) {
if (i === 3) continue;
[Link](i);
}
🎯 Interview Tip (One-line)
Conditionals decide what to execute
Loops decide how many times to execute
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
✅ FUNCTIONS IN JAVASCRIPT
🔹 What is a Function?
✅ Definition
A function is a block of reusable code designed to perform a specific task.
It executes only when it is called (invoked).
🔹 Why Functions are needed?
Avoid code repetition
Improve readability
Make code modular
Easy maintenance
🔹 Basic Syntax
function functionName(parameters) {
// code
return value;
}
🔹 Example
function add(a, b) {
return a + b;
}
add(10, 20); // 30
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
✅ TYPES OF FUNCTIONS IN
JAVASCRIPT
1️⃣ Function Declaration (Named Function)
🔹 Definition
A function defined using the function keyword with a name.
🔹 Syntax
function functionName() {
}
🔹 Example
function greet() {
[Link]("Hello World");
}
greet();
🔹 Interview Point ⭐
Hoisted (can be called before definition)
2️⃣ Function Expression
🔹 Definition
A function assigned to a variable.
🔹 Syntax
const variableName = function() {
};
🔹 Example
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
const add = function(a, b) {
return a + b;
};
add(5, 3);
🔹 Interview Point ⭐
Not hoisted
3️⃣ Anonymous Function
🔹 Definition
A function without a name, usually used as a value.
🔹 Example
setTimeout(function() {
[Link]("Executed");
}, 1000);
4️⃣ Arrow Function (ES6)
🔹 Definition
A shorter syntax for writing functions using =>. Without function keyword
🔹 Syntax
const func = () => {
};
🔹 Example
const multiply = (a, b) => a * b;
🔹 Interview Points ⭐
No this binding
Cleaner syntax
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
5️⃣ Function with Parameters
🔹 Example
function square(num) {
return num * num;
}
square(4); // 16
6️⃣ Function with Return Value
🔹 Example
function sum(a, b) {
return a + b;
}
7️⃣ Default Parameter Function (ES6)
🔹 Definition
Provides default values to parameters.
🔹 Example
function greet(name = "Guest") {
[Link]("Hello", name);
}
greet(); // Hello Guest
8. Callback Function
🔹 Definition
A function passed as an argument to another function.
🔹 Example
function greet(name, callback) {
callback();
}
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
greet("Raj", function() {
[Link]("Welcome!");
});
9. Higher Order Function
🔹 Definition
A function that accepts another function or returns a function.
🔹 Example
function calculator(operation) {
return function(a, b) {
return operation(a, b);
};
}
1️0. IIFE (Immediately Invoked Function Expression)
🔹 Definition
A function that runs immediately after creation.
🔹 Syntax
(function() {
// code
})();
🔹 Example
(function() {
[Link]("Runs immediately");
})();
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
1️⃣1 Recursive Function
🔹 Definition
A Function that calls itself.
🔹 Example
function factorial(n) {
if (n === 1) return 1;
return n * factorial(n - 1);
}
🔥 Interview Comparison Table
Type Hoisted this
Function Declaration ✅ Yes Own
Function Expression ❌ No Own
Arrow Function ❌ No Lexical
🎯 Interview One-Liners ⭐
Functions are first-class citizens in JS.
Arrow functions don’t have this.
Callback functions enable async programming.
✅ PURE FUNCTIONS
🔹 Definition
A pure function is a function that:
1. Always returns the same output for the same input
2. Does not modify external state (no side effects)
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🔹 Rules of Pure Function ⭐
A function is pure if:
Output depends only on its input
Does not change global variables
Does not modify arguments
No I/O operations (console, API, DOM)
🔹 Example (Pure Function)
function add(a, b) {
return a + b;
}
add(2, 3); // 5
add(2, 3); // 5 (same output every time)
Another example:
function square(num) {
return num * num;
}
🔹 Why Pure Functions are good?
Easy to test
Easy to debug
Predictable behavior
Used heavily in React & Functional Programming
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
❌ IMPURE FUNCTIONS
🔹 Definition
An impure function is a function that:
Depends on or modifies external state
Produces different outputs for same input
Has side effects
🔹 Example (Impure Function)
let count = 0;
function increment() {
count++;
return count;
}
👉 Output depends on external variable count
Another example:
function logMessage(msg) {
[Link](msg); // side effect
}
🔹 Side Effects (Important ⭐)
Side effects include:
Modifying global variables
Changing DOM
API calls
Logging to console
Writing to files
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🔥 PURE vs IMPURE (Comparison Table)
Feature Pure Function Impure Function
Output Same for same input May change
Side effects ❌ No ✅ Yes
Global state Not used Used
Testable Easy Difficult
Predictability High Low
✅ Real-Life Example (Clear Difference)
❌ Impure
let tax = 10;
function calculatePrice(price) {
return price + tax;
}
✅ Pure
function calculatePrice(price, tax) {
return price + tax;
}
🎯 Interview One-Liners ⭐
Pure functions have no side effects.
Impure functions depend on external state.
React prefers pure components.
Reducers in Redux must be pure functions.
⚠️ Interview Trick Question
function randomNum() {
return [Link]();
}
👉 Impure (output changes every time)
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
✅ CLOSURES IN JAVASCRIPT
🔹 What is a Closure?
✅ Simple Definition
A closure is created when a function remembers variables from its outer scope even after
the outer function has finished execution.
👉 In simple words:
Inner function + outer function’s variables = Closure
🔹 Formal Definition (Interview-ready)
A closure is a function that has access to:
1. Its own scope
2. Outer function scope
3. Global scope
—even after the outer function is executed.
🔥 HOW CLOSURES WORK (Step-by-
Step)
Example 1️⃣ (Basic Closure)
function outer() {
let count = 0;
function inner() {
count++;
[Link](count);
}
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
return inner;
}
const fn = outer();
fn(); // 1
fn(); // 2
fn(); // 3
🔍 Explanation:
1. outer() executes and returns inner
2. Normally count should be destroyed
3. But JS keeps it in memory
4. inner() remembers count → closure created
🧠 WHY DOES JS DO THIS?
Because of:
Lexical scope
Garbage collection optimization
Functions are first-class citizens
✅ REAL-LIFE EXAMPLES
1️⃣ Data Encapsulation (Private Variables)
function bankAccount() {
let balance = 0;
return {
deposit(amount) {
balance += amount;
return balance;
},
withdraw(amount) {
return balance -= amount;
}
};
}
const account = bankAccount();
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
[Link](100);
[Link](30);
👉 balance is private ❌ cannot be accessed directly
2️⃣ Counter Example (Most Famous Interview Question)
function counter() {
let count = 0;
return function () {
return ++count;
};
}
const c = counter();
c(); // 1
c(); // 2
3️⃣ setTimeout + Closure Trap ⚠️
for (var i = 1; i <= 3; i++) {
setTimeout(() => {
[Link](i);
}, 1000);
}
❌ Output:
4
4
4
Fix using closure:
for (let i = 1; i <= 3; i++) {
setTimeout(() => {
[Link](i);
}, 1000);
}
or
for (var i = 1; i <= 3; i++) {
(function(i) {
setTimeout(() => {
[Link](i);
}, 1000);
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
})(i);
}
🔥 CLOSURE + LEXICAL SCOPE
function outer() {
let name = "Raj";
function inner() {
[Link](name);
}
return inner;
}
const fn = outer();
fn(); // Raj
👉 inner() remembers where it was defined
❓ INTERVIEW TRICK QUESTIONS
Q1️⃣ Is closure created only when returning a function?
❌ No
✔ Closure is created whenever an inner function accesses outer variables
Q2️⃣ Are closures memory expensive?
✔ Yes, if misused
👉 Always clean references when not needed
Q3️⃣ Is closure related to this?
❌ No directly
✔ But arrow functions inside closures behave differently
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🔥 ADVANTAGES OF CLOSURES
Data hiding
Encapsulation
Maintain state
Used in:
o Event handlers
o setTimeout / setInterval
o React hooks
o Redux
🎯 INTERVIEW ONE-LINERS ⭐
Closure is a function with preserved outer scope
JS uses lexical scoping
Closures help in data privacy
let helps avoid closure bugs
✅ HOISTING IN JAVASCRIPT
🔹 What is Hoisting?
✅ Simple Definition
Hoisting is JavaScript’s behavior of moving declarations to the top of their scope before
execution.
👉 Important:
Only declarations are hoisted, not initializations.
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🔹 How JavaScript Executes Code (Behind the Scenes)
JavaScript runs code in two phases:
1️⃣ Memory Creation Phase
Variables are allocated memory
Functions are stored completely
2️⃣ Execution Phase
Code runs line by line
Values are assigned
Hoisting happens in Memory Creation Phase.
✅ VARIABLE HOISTING
1️⃣ var Hoisting
Example
[Link](a);
var a = 10;
Output
undefined
Why?
Internally JS treats it like:
var a; // hoisted
[Link](a);
a = 10;
✔ var is hoisted and initialized with undefined
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
2️⃣ let and const Hoisting ⚠️
👉 let and const are hoisted but not initialized
Example
[Link](b);
let b = 20;
Output
ReferenceError: Cannot access 'b' before initialization
Why?
bis in Temporal Dead Zone (TDZ)
Accessible only after declaration line
🔥 Temporal Dead Zone (TDZ)
The time between entering scope and variable declaration is called TDZ.
{
[Link](x); // TDZ
let x = 5;
}
✅ FUNCTION HOISTING
3️⃣ Function Declaration Hoisting
Example
greet();
function greet() {
[Link]("Hello");
}
✔ Works fine because entire function is hoisted
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
4️⃣ Function Expression Hoisting
Example
sayHi();
var sayHi = function() {
[Link]("Hi");
};
❌ Error:
TypeError: sayHi is not a function
Why?
var sayHi; // hoisted
sayHi(); // undefined()
sayHi = function() {};
5️⃣ Arrow Function Hoisting
hello();
const hello = () => {
[Link]("Hello");
};
❌ Error: Cannot access before initialization
Arrow functions behave like let / const.
🔥 HOISTING SUMMARY TABLE
Declaration Type Hoisted Initialized Can Access Before
var ✅ undefined Yes
let ✅ ❌ No (TDZ)
const ✅ ❌ No (TDZ)
Function Declaration ✅ ✅ Yes
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
Declaration Type Hoisted Initialized Can Access Before
Function Expression Partial ❌ No
Arrow Function Partial ❌ No
⚠️ COMMON INTERVIEW TRAPS
❓ What is output?
[Link](typeof foo);
function foo() {}
✔ Output:
function
❓ What is output?
var x = 1;
function test() {
[Link](x);
var x = 2;
}
test();
✔ Output:
undefined
Why?
Local var x shadows global x
Hoisted to top of function
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🎯 INTERVIEW ONE-LINERS ⭐
Hoisting moves declarations, not values
var is hoisted with undefined
let & const are in TDZ
Function declarations are fully hoisted
✅ CURRYING IN JAVASCRIPT
🔹 What is Currying?
✅ Simple Definition
Currying is a technique where a function with multiple arguments is transformed into a
sequence of functions each taking one argument.
f(a, b, c) → f(a)(b)(c)
🔹 Why Currying is needed?
Reusability
Cleaner code
Function composition
Avoid passing same arguments again & again
Used in functional programming & React
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
✅ BASIC CURRYING EXAMPLE
❌ Normal Function
function add(a, b) {
return a + b;
}
✅ Curried Version
function add(a) {
return function(b) {
return a + b;
};
}
add(5)(3); // 8
👉 Inner function remembers a → closure 🔥
🔥 USING ARROW FUNCTIONS
(Cleanest Way)
const multiply = a => b => a * b;
multiply(2)(5); // 10
✅ REAL-LIFE USE CASE
Reusability Example
const discount = rate => price => price - price * rate;
const tenPercentOff = discount(0.1);
tenPercentOff(100); // 90
tenPercentOff(200); // 180
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
✅ CURRYING VS PARTIAL
APPLICATION
Currying Partial Application
One argument at a time Fix some arguments
f(a)(b) f(a, b)
Returns nested functions Returns one function
Example (Partial):
function add(a, b) {
return a + b;
}
const addFive = [Link](null, 5);
addFive(10); // 15
🔥 GENERIC CURRY FUNCTION
(INTERVIEW LEVEL)
function curry(fn) {
return function curried(...args) {
if ([Link] >= [Link]) {
return fn(...args);
}
return function(...next) {
return curried(...args, ...next);
};
};
}
Usage:
function sum(a, b, c) {
return a + b + c;
}
const curriedSum = curry(sum);
curriedSum(1)(2)(3);
curriedSum(1, 2)(3);
curriedSum(1)(2, 3);
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
❓ INTERVIEW QUESTIONS
Q⃣ Is currying possible without closure?
❌ No
✔ Currying uses closures
Q⃣ Is currying only one argument at a time?
✔ Typically yes (classic currying)
Q⃣ Does JS support currying by default?
❌ No
✔ Implement manually or use libraries like Lodash
🎯 INTERVIEW ONE-LINERS ⭐
Currying transforms a multi-argument function into nested single-argument functions
Uses closures
Improves reusability and readability
Common in functional programming
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
✅ DOM (Document Object Model)
🔹 What is DOM?
✅ Definition
The DOM (Document Object Model) is a programming interface that represents an
HTML document as a tree of objects, allowing JavaScript to access, modify, add, or delete
HTML elements dynamically.
👉 Simple words:
DOM connects HTML + JavaScript
🔹 Why DOM is needed?
Without DOM:
HTML would be static
No interactivity
With DOM:
Change text dynamically
Change styles
Handle user events
Create interactive websites
🔹 How DOM Works?
1. Browser loads HTML
2. Browser creates DOM Tree
3. JavaScript interacts with DOM using document
4. Changes reflect on the webpage instantly
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🌳 DOM TREE STRUCTURE
document
└── html
├── head
│ └── title
└── body
├── h1
└── p
🔹 Key Objects in DOM
Object Purpose
document Entry point of DOM
element HTML element
node Everything in DOM
window Browser object
✅ ACCESSING DOM ELEMENTS
1️⃣ getElementById
[Link]("title");
2️⃣ getElementsByClassName
[Link]("box");
3️⃣ getElementsByTagName
[Link]("p");
4️⃣ querySelector ⭐ (Most Used)
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
[Link](".box");
[Link]("#id");
[Link]("p");
5️⃣ querySelectorAll
[Link]("li");
✅ DOM MANIPULATION
🔹 Change Content
innerText
[Link] = "Hello";
textContent
[Link] = "Hello";
innerHTML
[Link] = "<b>Hello</b>";
🔹 Change Styles
[Link] = "red";
[Link] = "yellow";
🔹 Add / Remove Classes
[Link]("active");
[Link]("active");
[Link]("active");
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
✅ DOM ATTRIBUTES (set, get, remove)
🔹 What are Attributes?
✅ Definition
Attributes provide extra information about HTML elements (like id, class, src, href,
type, etc.).
Example:
<img src="[Link]" alt="image">
1️⃣ GET ATTRIBUTE
🔹 getAttribute()
Syntax
[Link]("attributeName");
Example
const img = [Link]("img");
[Link]("src"); // "[Link]"
🔹 Check if attribute exists
[Link]("disabled"); // true / false
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
2️⃣ SET ATTRIBUTE
🔹 setAttribute()
Syntax
[Link]("attributeName", "value");
Example
const link = [Link]("a");
[Link]("href", "[Link]
[Link]("target", "_blank");
🔹 Change existing attribute
[Link]("alt", "Profile image");
3️⃣ REMOVE ATTRIBUTE
🔹 removeAttribute()
Syntax
[Link]("attributeName");
Example
[Link]("disabled");
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🔥 REAL-TIME EXAMPLES
Example 1️⃣ Disable button
[Link]("disabled", "true");
Example 2️⃣ Enable button
[Link]("disabled");
Example 3️⃣ Toggle attribute
if ([Link]("readonly")) {
[Link]("readonly");
} else {
[Link]("readonly", "true");
}
⚠️ ATTRIBUTE vs PROPERTY
(INTERVIEW ⭐)
[Link] = "Hello"; // property
[Link]("value","Hello"); // attribute
Attribute Property
HTML JS object
String Can be any type
Static Dynamic
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🔥 CLASS & ID (Special Case)
❌ Avoid this:
[Link]("class", "box");
✅ Prefer this:
[Link]("box");
[Link]("box");
🎯 INTERVIEW ONE-LINERS ⭐
getAttribute() reads attribute value
setAttribute() adds or updates attribute
removeAttribute() deletes attribute
classList is better for class handling
🔹 Create & Add Elements
const div = [Link]("div");
[Link] = "New Element";
[Link](div);
✅ HOW TO APPEND ELEMENTS IN
DIFFERENT PLACES (DOM)
🔹 Step 1: Create an Element
const newDiv = [Link]("div");
[Link] = "I am a new element";
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
1️⃣ Append at the END of an element
appendChild()
[Link](newDiv);
✔ Adds as last child
append() (Modern)
[Link](newDiv);
✔ Can append multiple nodes / text
2️⃣ Append at the BEGINNING of an
element
prepend()
[Link](newDiv);
✔ Adds as first child
3️⃣ Append BEFORE a specific element
before()
[Link](newDiv);
✔ Adds before target element
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
4️⃣ Append AFTER a specific element
after()
[Link](newDiv);
✔ Adds after target element
5️⃣ Insert at ANY POSITION (Most
Powerful ⭐)
insertAdjacentElement()
[Link]("beforebegin", newDiv);
Possible Positions:
Position Where
beforebegin Before element
afterbegin Inside, at start
beforeend Inside, at end
afterend After element
Example:
[Link]("afterbegin", newDiv);
6️⃣ Insert HTML directly
insertAdjacentHTML()
[Link]("beforeend", "<p>Hello</p>");
⚠️ Be careful with user input (XSS risk)
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🔥 REAL-TIME EXAMPLES
Example 1️⃣: Add item to list end
const li = [Link]("li");
[Link] = "New Item";
[Link](li);
Example 2️⃣: Add item at top
[Link](li);
Example 3️⃣: Insert after a heading
const h1 = [Link]("h1");
[Link](newDiv);
⚠️ IMPORTANT INTERVIEW NOTE
❗ An element cannot exist in two places at once
[Link](newDiv);
[Link](newDiv); // moves element, doesn't copy
✔ To duplicate:
const clone = [Link](true);
[Link](clone);
🔥 COMPARISON TABLE
Method Position Old/Modern
appendChild End Old
append End Modern
prepend Start Modern
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
Method Position Old/Modern
before Before element Modern
after After element Modern
insertAdjacentElement Anywhere Powerful
🎯 INTERVIEW ONE-LINERS ⭐
appendChild() adds at end
prepend() adds at beginning
before() and after() add outside
insertAdjacentElement() gives full control
🔹 Remove Elements
[Link]();
⚠️ DOM INTERVIEW TRAPS
❓ innerText vs textContent
innerText → respects CSS
textContent → faster, ignores CSS
❓ querySelector vs getElementById
querySelector → CSS selector
getElementById → faster, ID only
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🎯 INTERVIEW ONE-LINERS ⭐
DOM represents HTML as objects
JavaScript manipulates HTML via DOM
document is the root object
DOM enables dynamic webpages
✅ EVENTS IN JAVASCRIPT (Complete
Guide)
1️⃣ EVENT
🔹 Definition
An event is an action or occurrence that happens in the browser due to the user or the system.
🔹 Examples of Events
click
submit
keydown
mouseover
load
change
🔹 Example
[Link] = function () {
alert("Button clicked");
};
2️⃣ EVENT HANDLER
🔹 Definition
An event handler is a function that runs when an event occurs.
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🔹 Example
function showMsg() {
alert("Hello");
}
Used as:
<button >
👉 This method is not recommended now.
3️⃣ EVENT LISTENER ⭐ (Most Used)
🔹 Definition
An event listener listens/wait for a specific event and executes a function when the event
occurs.
🔹 Syntax
[Link](event, handler, useCapture);
🔹 Example
[Link]("click", function () {
[Link]("Clicked");
});
✔ Recommended
✔ Allows multiple listeners
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🔥 EVENT PROPAGATION
(IMPORTANT)
🔹 Definition
Event propagation is the order in which an event travels through the DOM tree.
There are 3 phases:
1. Capturing
2. Target
3. Bubbling
4️⃣ EVENT CAPTURING (Trickling Phase)
🔹 Definition
Event travels from document → target element.
🔹 Syntax
[Link]("click", handler, true);
🔹 Example
[Link]("click", () => {
[Link]("Parent capturing");
}, true);
5️⃣ EVENT BUBBLING (Default)
🔹 Definition
Event travels from target → document.
🔹 Syntax
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
[Link]("click", handler, false);
🔹 Example
[Link]("click", () => {
[Link]("Child clicked");
});
[Link]("click", () => {
[Link]("Parent clicked");
});
✔ Bubbling is default behavior
🔥 EVENT PROPAGATION FLOW
(Visual)
Capturing Phase
document → body → parent → child
Target Phase
child
Bubbling Phase
child → parent → body → document
6️⃣ STOP EVENT PROPAGATION
[Link]();
Prevents event from moving further.
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
7️⃣ EVENT DELEGATION ⭐⭐⭐ (Very
Important)
🔹 Definition
Event delegation is a technique where a single event listener is added to a parent element
to handle events of its child elements using event bubbling.
🔹 Why use Event Delegation?
Better performance
Handles dynamically added elements
Less memory usage
🔹 Example
[Link]("click", function (e) {
if ([Link] === "LI") {
[Link]([Link]);
}
});
🔹 Real-life Example
Todo list
Menu clicks
Table rows
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
⚠️ EVENT HANDLER vs EVENT
LISTENER (Interview)
Event Handler Event Listener
onclick addEventListener
Only one Multiple allowed
Old Modern
🎯 INTERVIEW ONE-LINERS ⭐
Events make pages interactive
Bubbling is default
Capturing uses true
Event delegation uses bubbling
[Link] tells actual element clicked
✅ ARRAY IN JAVASCRIPT
🔹 What is an Array?
✅ Definition
An array is a data structure used to store multiple values in a single variable.
In javascript array we can store any type of data
let fruits = ["apple", "banana", "mango",132,true];
🔹 Why Arrays?
Store multiple values
Access using index
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
Easy data manipulation
Used everywhere (lists, tables, APIs)
✅ ARRAY DECLARATION
1️⃣ Using Array Literal (Recommended)
let numbers = [10, 20, 30];
2️⃣ Using new Array()
let nums = new Array(1, 2, 3);
⚠️ Avoid this for beginners
let nums = new Array(1); 1 considered as length of the array
✅ BASIC ARRAY OPERATIONS
(WITHOUT METHODS)
🔹 Access Elements
let arr = [10, 20, 30];
[Link](arr[0]); // 10
[Link](arr[2]); // 30
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🔹 Modify Elements
arr[1] = 50;
[Link](arr); // [10, 50, 30]
🔹 Add Element at End (Index method)
arr[[Link]] = 40;
🔹 Add Element at Beginning
arr[0] = 5; // overwrites first element ❌
(Proper way is using methods — explained below)
🔹 Loop Through Array
for loop
for (let i = 0; i < [Link]; i++) {
[Link](arr[i]);
}
for...of
for (let value of arr) {
[Link](value);
}
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
JavaScript Array Methods
1. push()
Definition: Adds one or more elements to the end of an array.
Syntax:
[Link](element1, element2)
Example:
let arr = [1, 2];
[Link](3);
// [1, 2, 3]
2. pop()
Definition: Removes the last element from an array.
Syntax:
[Link]()
Example:
let arr = [1, 2, 3];
[Link]();
// [1, 2]
3. unshift()
Definition: Adds elements to the beginning of an array.
Syntax:
[Link](element)
Example:
let arr = [2, 3];
[Link](1);
// [1, 2, 3]
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
4. shift()
Definition: Removes the first element from an array.
Syntax:
[Link]()
Example:
let arr = [1, 2, 3];
[Link]();
// [2, 3]
5. length
Definition: Returns the number of elements in an array.
Syntax:
[Link]
Example:
let arr = [10, 20, 30];
[Link]; // 3
6. indexOf()
Definition: Returns the index of the first occurrence of an element.
Syntax:
[Link](value)
Example:
let arr = [10, 20, 30];
[Link](20); // 1
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
7. includes()
Definition: Checks if an array contains a specific element.
Syntax:
[Link](value)
Example:
[Link](30); // true
8. slice()
Definition: Returns a new array by extracting a portion of an array.
Syntax:
[Link](start, end)
Example:
let arr = [1, 2, 3, 4];
[Link](1, 3); // [2, 3]
9. splice()
Definition: Adds/removes elements from an array (changes original array).
Syntax:
[Link](start, deleteCount, item)
Example:
let arr = [1, 2, 3];
[Link](1, 1, 99);
// [1, 99, 3]
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
10. concat()
Definition: Merges two or more arrays into a new array.
Syntax:
[Link](array2)
Example:
[1, 2].concat([3, 4]); // [1, 2, 3, 4]
toString():
Definition: This method is used to convert array to string. And this method always separates
elements with commas.
Ex:[Link]([Link]()) // 10,20,30
11. join()
Definition: Converts array elements into a string.
Syntax:
[Link](separator)
Example:
['a', 'b', 'c'].join('-'); // "a-b-c"
12. reverse()
Definition: Reverses the order of elements.
Syntax:
[Link]()
Example:
[1, 2, 3].reverse(); // [3, 2, 1]
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
13. sort()
Definition: Sorts array elements.
Syntax:
[Link](compareFn)
Example:
[3, 1, 2].sort((a, b) => a - b); // [1, 2, 3]
14. forEach()
Definition: Executes a function for each element.
forEach never return anything
Syntax:
[Link](callback)
Example:
[1, 2, 3].forEach(n => [Link](n));
15. map()
Definition: Creates a new array by transforming each element.
Syntax:
[Link](callback)
Example:
[1, 2, 3].map(n => n * 2); // [2, 4, 6]
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
16. filter()
Definition: Creates a new array with elements that pass a condition.
Syntax:
[Link](callback)
Example:
[1, 2, 3, 4].filter(n => n % 2 === 0); // [2, 4]
17. reduce()
Definition: Reduces array to a single value.
Syntax:
[Link]((acc, curr) => value, initialValue)
Example:
[1, 2, 3].reduce((sum, n) => sum + n, 0); // 6
18. find()
Definition: Returns the first element that matches condition.
Syntax:
[Link](callback)
Example:
[10, 20, 30].find(n => n > 15); // 20
19. findIndex()
Definition: Returns index of first matching element.
Syntax:
[Link](callback)
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
Example:
[10, 20, 30].findIndex(n => n > 15); // 1
20. some()
Definition: Checks if any element satisfies condition.
Syntax:
[Link](callback)
Example:
[1, 2, 3].some(n => n > 2); // true
21. every()
Definition: Checks if all elements satisfy condition.
Syntax:
[Link](callback)
Example:
[2, 4, 6].every(n => n % 2 === 0); // true
🎯 Interview Summary
map, filter, reduce return new array/value
slice does not mutate, splice mutates
forEach does not return anything
reduce is the most powerful array method
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🔹 What is an Object in JavaScript?
An object is a collection of key–value pairs used to store related data and functionality
together in a single variable.
👉 Think of an object as a real-world entity.
Example (Real life):
A person has a name, age, and skills.
🔹 Object Example
const person = {
name: "Raj",
age: 24,
skills: ["HTML", "CSS", "JavaScript"],
isDeveloper: true
};
Here:
name, age, skills, isDeveloper → properties
"Raj", 24, [...], true → values
🔹 Why Objects Are Used?
Objects are used to:
Group related data
Represent real-world entities
Make code more structured and readable
Store data + behavior together
🔹 Creating Objects in JavaScript
1️⃣ Object Literal (Most Common)
const car = {
brand: "Toyota",
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
model: "Innova",
year: 2023
};
✔ Most used in real projects
✔ Easy and readable
2️⃣ Using new Object()
const user = new Object();
[Link] = "Naga";
[Link] = "Frontend Developer";
❌ Less commonly used
🔹 Accessing Object Properties
Dot Notation (Preferred)
[Link]([Link]); // Raj
Bracket Notation
[Link](person["age"]); // 24
👉 Use bracket notation when:
Property name has spaces
Property name is dynamic
🔹 Adding, Updating & Deleting Properties
Add
[Link] = "Hyderabad";
Update
[Link] = 25;
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
Delete
delete [Link];
🔹 Objects with Methods (Functions inside Object)
const student = {
name: "Anil",
marks: 85,
getResult: function () {
return [Link] >= 40 ? "Pass" : "Fail";
}
};
[Link]([Link]()); // Pass
👉 Function inside object = method
👉 this refers to current object
🔹 this Keyword (Very Important)
✅ Definition of this keyword in JavaScript
this refers to the object that is currently calling the function.
⭐ Interview-friendly one-liner
In JavaScript, this is a keyword that points to the object that owns or invokes the
current function.
🔹 Simple understanding
this = who is calling the function
Its value depends on how and where the function is executed
const employee = {
name: "Raj",
greet() {
[Link]("Hello " + [Link]);
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
}
};
[Link](); // Hello Raj
✔ [Link] → refers to [Link]
🔹 Looping Through an Object
Using for...in
for (let key in person) {
[Link](key, person[key]);
}
🔹 Object Methods (Commonly Used)
Method Purpose
[Link](obj) Returns all keys
[Link](obj) Returns all values
[Link](obj) Returns key-value pairs
hasOwnProperty() Checks property exists
Example:
[Link](person); // ["name", "age", "skills"]
🔹 Object vs Array (Interview Favorite)
Object Array
Key–value pairs Index-based
Stores related info Stores list of values
Unordered Ordered
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🔹 Objects Are Reference Types ⚠️
const a = { x: 10 };
const b = a;
b.x = 20;
[Link](a.x); // 20
👉 Both point to same memory
🔹 Where Objects Are Used in Real Projects?
User profiles
API responses (JSON)
Form data
Configuration settings
State management (React)
🔹 One-Line Interview Definition ⭐
An object in JavaScript is a non-primitive data type that stores data in key-value pairs
and represents real-world entities.
🔹 Spread Operator (...)
✅ Definition
The spread operator expands (spreads) elements of an array or properties of an object
into individual values.
📌 Where Spread is Used
Copy arrays / objects
Merge arrays / objects
Pass values to functions
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🔹 Spread with Arrays
const skills = ["HTML", "CSS"];
const newSkills = [...skills, "JavaScript"];
[Link](newSkills);
// ["HTML", "CSS", "JavaScript"]
✔ Creates a new array
✔ Original array is not modified
🔹 Spread with Objects
const person = { name: "Raj", age: 24 };
const updatedPerson = {
...person,
city: "Hyderabad"
};
[Link](updatedPerson);
✔ Used heavily in React state updates
🔹 Merge Arrays
const a = [1, 2];
const b = [3, 4];
const merged = [...a, ...b];
🔹 Spread in Function Call
const nums = [10, 20, 30];
[Link](...nums); // 30
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🔹 Rest Operator (...)
✅ Definition
The rest operator collects multiple values into a single array or object.
📌 Where Rest is Used
Function parameters
Destructuring
🔹 Rest in Function Parameters
function add(...numbers) {
return [Link]((sum, n) => sum + n, 0);
}
add(1, 2, 3, 4); // 10
✔ Collects all arguments into numbers array
🔹 Rest in Array Destructuring
const skills = ["HTML", "CSS", "JS", "React"];
const [first, second, ...remaining] = skills;
[Link](remaining); // ["JS", "React"]
🔹 Rest in Object Destructuring
const person = {
name: "Raj",
age: 24,
city: "Hyd"
};
const { name, ...restDetails } = person;
[Link](restDetails);
// { age: 24, city: "Hyd" }
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🔹 Spread vs Rest (Interview Must-Know)
Spread Rest
Expands values Collects values
Used on right side Used on left side
Used while copying Used while receiving
🔹 One-Line Interview Answers ⭐
Spread:
Used to expand elements of arrays or objects.
Rest:
Used to collect remaining elements into an array or object.
🔹 Very Common Interview Question ❗
Q: Are spread and rest operators same?
A:
They use the same syntax (...) but spread expands values, while rest collects values.
🔹 What is Destructuring in JavaScript?
Destructuring is a syntax that allows you to extract values from arrays or properties
from objects and store them in variables in a simple way.
🔹 Why Destructuring is Used?
Makes code short and readable
Avoids repeated dot notation
Very common in React & modern JS
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
Improves clarity in function parameters
🔹 Array Destructuring
Basic Example
const skills = ["HTML", "CSS", "JavaScript"];
const [skill1, skill2, skill3] = skills;
[Link](skill1); // HTML
Skip Values
const [first, , third] = skills;
[Link](third); // JavaScript
Default Values
const [a, b, c = "React"] = ["HTML", "CSS"];
[Link](c); // React
Using Rest with Destructuring
const [mainSkill, ...otherSkills] = skills;
[Link](otherSkills);
// ["CSS", "JavaScript"]
🔹 Object Destructuring
Basic Example
const person = {
name: "Raj",
age: 24,
city: "Hyderabad"
};
const { name, age } = person;
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
[Link](name); // Raj
Rename Variables
const { name: fullName, age: years } = person;
[Link](fullName); // Raj
Default Values
const { country = "India" } = person;
[Link](country); // India
Using Rest with Objects
const { name, ...otherDetails } = person;
[Link](otherDetails);
// { age: 24, city: "Hyderabad" }
🔹 Destructuring in Function Parameters (Very Important
⭐)
Object Example
function displayUser({ name, age }) {
[Link](name, age);
}
displayUser(person);
Array Example
function showSkills([first, second]) {
[Link](first, second);
}
showSkills(skills);
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🔹 Real-World / React Example
const props = {
title: "Profile",
isLoggedIn: true
};
function Header({ title, isLoggedIn }) {
return <h1>{title}</h1>;
}
✔ Extremely common in React interviews
🔹 Destructuring vs Normal Way
❌ Without destructuring:
const name = [Link];
const age = [Link];
✅ With destructuring:
const { name, age } = person;
🔹 One-Line Interview Definition ⭐
Destructuring is a JavaScript feature that allows extracting values from arrays or
properties from objects into variables in a concise way.
🔹 Common Interview Questions
Difference between array and object destructuring?
Can we set default values in destructuring?
How does rest work with destructuring?
Is destructuring shallow or deep?
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🔹 What is Copy in JavaScript?
Copying means creating a new variable from an existing object or array.
👉 JavaScript objects & arrays are reference types, so copying must be done carefully.
🔹 Shallow Copy
✅ Definition
A shallow copy creates a new object, but nested objects still share the same memory
reference.
Copy only top level elements
🔹 Example (Shallow Copy)
const person = {
name: "Raj",
skills: ["HTML", "CSS"]
};
const copyPerson = { ...person };
[Link]("JavaScript");
[Link]([Link]);
// ["HTML", "CSS", "JavaScript"]
❗ Problem:
Outer object is copied
Inner array (skills) is shared
🔹 Ways to Create Shallow Copy
Spread operator (...)
[Link]()
[Link]()
[Link]()
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
Example:
const shallow = [Link]({}, person);
🔹 Deep Copy
✅ Definition
A deep copy creates a completely independent copy, including all nested objects and
arrays.
🔹 Example (Deep Copy)
const person = {
name: "Raj",
skills: ["HTML", "CSS"]
};
const deepCopy = [Link]([Link](person));
[Link]("JavaScript");
[Link]([Link]);
// ["HTML", "CSS"]
✔ Original object not affected
🔹 Ways to Create Deep Copy
1️⃣ Using [Link]([Link]())
✔ Simple
❌ Cannot copy functions, undefined, Date
2️⃣ Using structuredClone() (Modern & Best)
const deepCopy = structuredClone(person);
✔ Handles nested objects well
✔ Recommended in modern JS
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
3️⃣ Manual / Recursive Method (Advanced)
function deepClone(obj) {
return structuredClone(obj);
}
🔹 Shallow vs Deep Copy (Interview Favorite ⭐)
Shallow Copy Deep Copy
Copies top-level only Copies all levels
Shares nested references No shared references
Faster Slightly slower
Spread / assign structuredClone
🔹 One-Line Interview Answers ⭐
Shallow Copy:
Copies only the first level; nested objects share reference.
Deep Copy:
Copies all levels, creating a fully independent object.
🔹 Common Interview Question ❗
Q: Does spread operator create deep copy?
A:
❌ No, spread operator creates a shallow copy.
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🔹 Real-World Usage
Shallow copy: State updates with flat objects
Deep copy: Complex nested data, form data, undo/redo features
Call(), Apply() and Bind() methods.
🔹 Why call, apply, bind are Needed?
In JavaScript, the value of this depends on how a function is called.
call, apply, and bind allow us to manually set the value of this.
🔹 Common Definition (One Line ⭐)
call, apply, and bind are methods used to control the value of this inside a function.
🔹 Example Function
function introduce(city, country) {
[Link]([Link] + " from " + city + ", " + country);
}
const person = { name: "Raj" };
🔹 call()
✅ Definition
call() invokes the function immediately and accepts arguments one by one.
Syntax
[Link](thisValue, arg1, arg2);
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
Example
[Link](person, "Hyderabad", "India");
// Raj from Hyderabad, India
🔹 apply()
✅ Definition
apply() invokes the function immediately and accepts arguments as an array.
Syntax
[Link](thisValue, [arg1, arg2]);
Example
[Link](person, ["Hyderabad", "India"]);
// Raj from Hyderabad, India
🔹 bind()
✅ Definition
bind()returns a new function with this permanently bound; it does not execute
immediately.
Syntax
const newFn = [Link](thisValue, arg1, arg2);
Example
const boundFn = [Link](person, "Hyderabad", "India");
boundFn();
// Raj from Hyderabad, India
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🔹 Key Differences (Interview Favorite ⭐)
Method Executes Immediately Arguments Returns
call ✅ Yes Individual Function result
apply ✅ Yes Array Function result
bind ❌ No Individual New function
🔹 Real-World Use Cases
call: Borrow methods from another object
apply: Use array data (e.g., [Link])
bind: Event handlers, React callbacks
🔹 Example: Method Borrowing
const user1 = { name: "Raj" };
const user2 = { name: "Anil" };
function greet() {
[Link]("Hello " + [Link]);
}
[Link](user2); // Hello Anil
🔹 Very Common Interview Questions ❗
Q: Does bind() call the function immediately?
A: ❌ No, it returns a new function.
Q: Difference between call and apply?
A: Arguments: call → comma separated, apply → array.
🔹 One-Line Interview Answers ⭐
call: Calls function immediately with custom this.
apply: Same as call but arguments are passed as array.
bind: Returns a new function with fixed this.
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
✅ 1️⃣ What is Asynchronous Operation?
An asynchronous operation is a task that runs in the background without blocking the
execution of other code.
👉 JavaScript does not wait for the task to finish.
👉 It continues executing the next lines of code.
🧠 Why Do We Need It?
Some operations take time:
Fetching data from API
Reading files
Database queries
Timers
User input
If JavaScript waits for them, the whole application will freeze.
So JavaScript uses asynchronous behavior to stay fast and non-blocking.
⚡ 2️⃣ Synchronous vs Asynchronous
🛑 Synchronous (Blocking)
[Link]("Start");
function slowTask() {
for (let i = 0; i < 1000000000; i++) {}
}
slowTask();
[Link]("End");
Output:
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
Start
End (after delay)
👉 Here, JS waits for slowTask() to finish.
🚀 Asynchronous (Non-Blocking)
[Link]("Start");
setTimeout(() => {
[Link]("Inside Timeout");
}, 2000);
[Link]("End");
Output:
Start
End
Inside Timeout (after 2 seconds)
👉 JS does NOT wait for setTimeout().
🔥 3️⃣ How JavaScript Handles Async?
JavaScript is:
Single-threaded
Uses Event Loop
Uses Web APIs (Browser / Node APIs)
Flow:
1. Code runs in Call Stack
2. Async task goes to Web API
3. After completion → Callback Queue
4. Event Loop pushes it back to Call Stack
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🎯 4️⃣ Ways to Handle Asynchronous
Operations
There are 3 main ways:
1. Callbacks
2. Promises
3. Async/Await
1️⃣ Callbacks
A callback is a function passed as an argument to another function.
✅ Syntax
function fetchData(callback) {
setTimeout(() => {
[Link]("Data fetched");
callback();
}, 2000);
}
fetchData(function () {
[Link]("Process data");
});
Output:
Data fetched
Process data
❌ Problem: Callback Hell
login(user, function() {
getProfile(function() {
getPosts(function() {
logout();
});
});
});
Hard to read and maintain.
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
2️⃣ Promises
A Promise represents a value that may be available now, later, or never.
A Promise is an object that represents the eventual result of an asynchronous operation.
👉 It may complete now
👉 Or later
👉 Or may fail
🧠 Simple Definition (Interview Ready)
A Promise is an object that handles asynchronous operations and provides a way to manage
success and failure results.
✅ Promise States
Pending
Fulfilled
Rejected
✅ Syntax – Creating a Promise
let myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Operation successful");
} else {
reject("Operation failed");
}
});
✅ Consuming a Promise
myPromise
.then((result) => {
[Link](result);
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
})
.catch((error) => {
[Link](error);
});
✅ Real Example
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data received");
}, 2000);
});
}
fetchData()
.then(data => [Link](data));
3️⃣ Async / Await (Modern Way)
This is built on top of Promises.
Makes async code look synchronous.
✅ Syntax
async function fetchData() {
return "Hello";
}
👉 async function always returns a Promise.
✅ Using Await
function getData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Data loaded");
}, 2000);
});
}
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
async function displayData() {
let result = await getData();
[Link](result);
}
displayData();
✅ Error Handling with try/catch
async function fetchData() {
try {
let response = await getData();
[Link](response);
} catch (error) {
[Link](error);
}
}
🧠 5️⃣ Real Example – Fetch API
async function getUsers() {
let response = await fetch("[Link]
let data = await [Link]();
[Link](data);
}
getUsers();
🔥 Interview Important Points
✔ JavaScript is single-threaded
✔ Async makes it non-blocking
✔ Uses Event Loop
✔ Promises avoid callback hell
✔ Async/await is syntactic sugar over promises
✔ await works only inside async functions
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🏁 Final Comparison
Method Readability Error Handling Modern?
Callback ❌ Low ❌ Difficult Old
Promise ✅ Good ✅ Better Yes
Async/Await ✅✅ Very Clean ✅✅ Easy Best
Let’s understand:
✅ Call Stack
✅ Web APIs
✅ Callback Queue
✅ Microtask Queue
✅ Event Loop
✅ How everything works together
🔥 First Important Point
JavaScript is:
Single-threaded
Synchronous by default
But behaves asynchronous using the Event Loop
🧠 1️⃣ Call Stack (Execution Stack)
👉 The Call Stack is where JavaScript executes code line by line.
It follows:
LIFO (Last In First Out)
Example:
function first() {
[Link]("First");
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
function second() {
first();
[Link]("Second");
}
second();
Execution Order in Call Stack:
1. second() pushed
2. first() pushed
3. first() popped
4. second() popped
🌐 2️⃣ What are Web APIs?
JavaScript engine (like V8) does NOT handle:
setTimeout
DOM events
fetch
AJAX
geolocation
These are provided by:
Browser Web APIs
[Link] APIs
So when JS sees:
setTimeout(() => {
[Link]("Hello");
}, 2000);
It sends it to Web API environment.
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🔄 3️⃣ Callback Queue (Macrotask Queue)
After the timer completes:
The callback goes to:
👉 Callback Queue (also called Task Queue or Macrotask Queue)
It waits there until Call Stack becomes empty.
⚡ 4️⃣ Microtask Queue (Very Important)
Used by:
Promises (.then, .catch)
queueMicrotask
MutationObserver
Microtask queue has higher priority than Callback Queue.
🔁 5️⃣ What is Event Loop?
The Event Loop continuously checks:
Is Call Stack empty?
YES → Check Microtask Queue
YES → Move Microtasks to Call Stack
THEN → Check Callback Queue
It keeps looping forever.
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
📦 Full Flow Diagram (Step by Step)
Call Stack
↓
Web APIs
↓
Microtask Queue (High Priority)
↓
Callback Queue (Low Priority)
↓
Event Loop checks continuously
🚀 Example 1️ – Simple setTimeout
[Link]("Start");
setTimeout(() => {
[Link]("Timeout");
}, 0);
[Link]("End");
Output:
Start
End
Timeout
Why?
1. "Start" → Call Stack
2. setTimeout → Web API
3. "End" → Call Stack
4. Stack empty
5. Event Loop moves callback from queue
6. "Timeout" prints
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🚀 Example 2️ – Promise vs setTimeout
(Important Interview Question)
[Link]("Start");
setTimeout(() => {
[Link]("Timeout");
}, 0);
[Link]().then(() => {
[Link]("Promise");
});
[Link]("End");
What is Output?
Start
End
Promise
Timeout
WHY? (Very Important)
1. Start → Stack
2. setTimeout → Web API
3. Promise → Microtask Queue
4. End → Stack
5. Stack empty
6. Event Loop checks Microtask Queue first → "Promise"
7. Then Callback Queue → "Timeout"
👉 Microtasks run BEFORE macrotasks.
🧠 Example 3️ – Multiple Promises
[Link]("Start");
[Link]().then(() => {
[Link]("First");
});
[Link]().then(() => {
[Link]("Second");
});
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
[Link]("End");
Output:
Start
End
First
Second
👉 All microtasks execute before moving to macrotask queue.
🏗 Real Life Analogy (Easy Understanding)
Think of it like:
🦴🍳 Chef (Call Stack)
📦 Helper (Web APIs)
📋 VIP Orders (Microtasks)
📋 Normal Orders (Macrotasks)
👀 Manager (Event Loop)
Manager rule:
If chef is free
Complete all VIP orders first
Then complete normal orders
🎯 Interview Important Points
✔ JavaScript is single-threaded
✔ Web APIs are not part of JS engine
✔ Event Loop makes async possible
✔ Microtasks have higher priority than macrotasks
✔ Promises run before setTimeout
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
💎 One More Tricky Question
setTimeout(() => [Link]("1"), 0);
[Link]().then(() => [Link]("2"));
[Link]("3");
Output:
3
2
1
If you understand WHY, you understand Event Loop completely.
Let’s understand:
✅ What is Callback Hell
✅ Why it is a problem
✅ How Promises solve it
✅ What is Promise Chaining
✅ Real practical examples
😵 1️⃣ What is Callback Hell?
Callback Hell happens when we nest callbacks inside callbacks inside callbacks…
It becomes:
Hard to read
Hard to debug
Hard to maintain
🚨 Example of Callback Hell
function login(user, callback) {
setTimeout(() => {
[Link]("User logged in");
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
callback();
}, 1000);
}
function getProfile(callback) {
setTimeout(() => {
[Link]("Profile fetched");
callback();
}, 1000);
}
function getPosts(callback) {
setTimeout(() => {
[Link]("Posts fetched");
callback();
}, 1000);
}
// Nested callbacks
login("Naga", function () {
getProfile(function () {
getPosts(function () {
[Link]("All done");
});
});
});
📤 Output
User logged in
Profile fetched
Posts fetched
All done
😵 Why This is Bad?
This shape is called the:
Pyramid of Doom
Because it keeps going deeper:
a(function(){
b(function(){
c(function(){
d(function(){
})
})
})
})
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
Problems:
Difficult error handling
Deep nesting
Code unreadable
Logic tightly coupled
🔥 2️⃣ How Promises Solve This
Instead of nesting, we return a Promise.
✅ Step 1️ – Convert to Promise
function login(user) {
return new Promise((resolve) => {
setTimeout(() => {
[Link]("User logged in");
resolve();
}, 1000);
});
}
function getProfile() {
return new Promise((resolve) => {
setTimeout(() => {
[Link]("Profile fetched");
resolve();
}, 1000);
});
}
function getPosts() {
return new Promise((resolve) => {
setTimeout(() => {
[Link]("Posts fetched");
resolve();
}, 1000);
});
}
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🔗 3️⃣ What is Promise Chaining?
Promise chaining means:
👉 Using .then() one after another
👉 Each .then() returns a new Promise
✅ Promise Chaining Example
login("Naga")
.then(() => getProfile())
.then(() => getPosts())
.then(() => [Link]("All done"))
.catch((error) => [Link](error));
📤 Output
User logged in
Profile fetched
Posts fetched
All done
💡 Why This is Better?
✔ No nesting
✔ Clean structure
✔ Centralized error handling
✔ Easy to read
🧠 Important Rule in Promise Chaining
Inside .then():
If you return a value → it goes to next .then()
If you return a Promise → next .then() waits for it
If you throw error → goes to .catch()
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
🎯 Example – Passing Data in Chain
function login(user) {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ userId: 101 });
}, 1000);
});
}
function getProfile(userId) {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ name: "Naga Raj" });
}, 1000);
});
}
login("Naga")
.then((data) => {
[Link](data);
return getProfile([Link]);
})
.then((profile) => {
[Link](profile);
})
.catch((err) => [Link](err));
⚠️ Common Mistake in Promise Chaining
❌ Forgetting to return:
login("Naga")
.then(() => {
getProfile(); // ❌ Not returning
})
.then(() => {
getPosts(); // Executes immediately (wrong)
});
👉 Always return:
.then(() => {
return getProfile();
})
OR shorter:
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
.then(getProfile)
🔥 Callback Hell vs Promise Chaining
Feature Callback Hell Promise Chaining
Structure Nested Linear
Readability Poor Clean
Error Handling Multiple places Single .catch()
Maintainability Difficult Easy
🚀 Bonus – Even Better: Async/Await
Promise chaining becomes even cleaner:
async function processUser() {
try {
await login("Naga");
await getProfile();
await getPosts();
[Link]("All done");
} catch (error) {
[Link](error);
}
}
processUser();
🏁 Interview Summary
If interviewer asks:
👉 What is Callback Hell?
Say:
When multiple asynchronous operations are nested inside callbacks, creating unreadable
pyramid-like code structure.
👉 How to avoid it?
Answer:
Nagaraja H T
Email:htnagaraja24@[Link]
Insta:Ka_14_Raj18
Using Promises and Promise chaining or async/await.