Javascript Explain
Javascript Explain
🧠 What is JavaScript?
👉 In simple terms:
HTML = structure
CSS = design
JavaScript = behavior (logic + interaction)
1. Dynamic Typing
let x = 10;
x = "hello";
User events
UI updates
4. First-Class Functions
function greet() {}
pass as argument
👉 Execution Context
nxt
👉 Think:
[Link]("Hello");
function test() {
[Link]("Hi");
}
test();
Variables → undefined
Example:
[Link](a);
var a = 10;
Internally:
var a = undefined;
[Link](a);
a = 10;
🔹 2. Execution Phase
Functions execute
⚡ Visual Flow
🧠 Example Breakdown
var a = 10;
function foo() {
var b = 20;
}
foo();
Step-by-step:
1. GEC created
2. Memory phase:
a = undefined
foo = function
3. Execution:
a = 10
4. Inside FEC:
b = undefined → then 20
nxt
🧠 Core Idea
👉 Think:
🧠 Basic Example
function one() {
two();
}
function two() {
[Link]("Hello");
}
one();
🔍 Step-by-step
7. Back to global
📊 Stack Flow
[ Global ]
→ [ one ]
→ [ two ]
→ pop two
→ pop one
→ back to Global
⚡ Real Insight
👉 Only one function runs at a time
function test() {
test();
}
test();
[Link]("A");
setTimeout(() => {
[Link]("B");
}, 0);
[Link]("C");
Output:
A
C
B
Why?
“The call stack is a LIFO structure that manages execution contexts, ensuring only one
function executes at a time, and it works with the event loop to handle asynchronous
operations.”
Next → Hoisting (this is where most candidates break)
nxt
🧠 Core Idea
Hoisting = JavaScript moves declarations to the top of their scope before execution
Type Behavior
🧠 Example 1 (var)
[Link](a);
var a = 10;
✅ Output
undefined
🧠 Why
Internally:
var a = undefined;
[Link](a);
a = 10;
🧠 Example 2 (function)
greet();
function greet() {
[Link]("Hi");
}
✅ Output
Hi
🧠 Why
[Link](b);
let b = 5;
❌ Output
ReferenceError
🧠 Why
var a → undefined
let b → TDZ
function → full function stored
“Hoisting is the behavior where JavaScript allocates memory for variables and functions
before execution, with var initialized as undefined and let/const remaining in the temporal
dead zone.”
nxt
🧠 Core Idea
⚙️ Simple Example
[Link](a);
let a = 10;
❌ Output
Memory Phase:
a → hoisted BUT not initialized (TDZ)
Execution Phase:
[Link](a) → ❌ still in TDZ
a = 10 → initialized → TDZ ends
🔥 Visual Timeline
Start scope
↓
[ TDZ ] → variable exists but unusable
↓
Initialization (let a = 10)
↓
Usable
🧠 Another Example
let x = 5;
function test() {
[Link](x);
let x = 10;
}
test();
❌ Output
ReferenceError
🧠 Why
[Link](a); // undefined
var a = 10;
✔ works because:
nxt
🧠 Core Idea
scope
hoisting
re-declaration
re-assignment
⚙️ 1. Scope Difference
{
var a = 10;
let b = 20;
const c = 30;
}
[Link](a); // ✅
[Link](b); // ❌
[Link](c); // ❌
🧠 Why
⚙️ 2. Hoisting Behavior
[Link](a); // undefined
var a = 10;
[Link](b); // ❌ ReferenceError
let b = 20;
🧠 Why
⚙️ 3. Re-declaration
var a = 10;
var a = 20; // ✅ allowed
let b = 10;
// let b = 20; ❌ error
⚙️ 4. Re-assignment
let x = 10;
x = 20; // ✅ allowed
const y = 10;
y = 20; // ❌ error
const a; // ❌ error
const b = 10; // ✅
🧠 Why
Re-declare ✅ ❌ ❌
Re-assign ✅ ✅ ❌
Feature var let const
Init required ❌ ❌ ✅
“var is function-scoped and hoisted with undefined, while let and const are block-scoped,
hoisted but restricted by the temporal dead zone, with const additionally preventing
reassignment.”
👉 Modern JS rule:
Avoid var
⚙️ 1. var
🧠 Behavior
Function scoped
var a = 10;
var a = 20; // ✅
a = 30; // ✅
⚠️ Problem
if (true) {
var x = 10;
}
[Link](x); // ✅ 10 (unexpected)
⚙️ 2. let
🧠 Behavior
Block scoped
Cannot re-declare
Can re-assign
let a = 10;
// let a = 20 ❌
a = 30; // ✅
if (true) {
let x = 10;
}
[Link](x); // ❌ error
⚙️ 3. const
🧠 Behavior
Block scoped
Cannot re-declare
Cannot re-assign
const a = 10;
// a = 20 ❌
⚠️ Important twist
⚡ Interview One-Liner
nxt
🧠 Core Idea
👉 Think:
“Where can I use this variable?”
⚙️ 1. Global Scope
Accessible everywhere
let a = 10;
function test() {
[Link](a);
}
test(); // 10
[Link](a); // 10
🧠 Insight
⚙️ 2. Function Scope
function test() {
let x = 20;
[Link](x); // 20
}
test();
[Link](x); // ❌ ReferenceError
🧠 Insight
⚙️ 3. Block Scope
if (true) {
let a = 10;
const b = 20;
}
[Link](a); // ❌
[Link](b); // ❌
if (true) {
var x = 10;
}
[Link](x); // ✅ 10
let a = 10;
function outer() {
function inner() {
[Link](a);
}
inner();
}
outer();
🧠 Why it works
JS looks:
1. inside function
3. then global
“Scope defines variable accessibility, with global scope available everywhere, function scope
limited to functions, and block scope restricting variables within blocks using let and const,
resolved through the scope chain.”
Types:
Number
String
Boolean
null
undefined
Symbol
BigInt
⚙️ Example
let a = 10;
let b = a;
b = 20;
[Link](a); // ?
[Link](b); // ?
✅ Output
10
20
🧠 Why
🧠 Memory View
a → 10
b → 10 (copy)
🧠 2. Reference (Non-Primitive)
Types:
Object
Array
Function
⚙️ Example
[Link] = "React";
[Link]([Link]); // ?
✅ Output
React
🧠 Why
🧠 Memory View
obj1 ─┐
├──> { name: "JS" }
obj2 ─┘
⚡ Key Difference
⚠️ Common Trap
let a = [1,2];
let b = [1,2];
✅ Output
false
🧠 Why
“Primitive types store actual values and are copied by value, whereas reference types store
memory addresses and are copied by reference, leading to shared mutations.”
let a = 10;
let b = a;
b = 20;
[Link](a); // ?
[Link](b); // ?
✅ Output:
10
20
👉 Why:
[Link] = "React";
[Link]([Link]); // ?
✅ Output:
React
👉 Why:
[Link](typeof null);
✅ Output:
"object"
👉 Why:
Historical JS bug
null is primitive but reported as "object"
👉 Interview line:
🔥 3. == vs ===
[Link](5 == "5");
[Link](5 === "5");
✅ Output:
true
false
🧠 Difference
👉 Rule:
== → dangerous
=== → safe
⚙️ Examples
[Link]("5" + 2); // ?
[Link]("5" - 2); // ?
✅ 3 → numeric conversion
[Link](true + 1); // ?
✅ 2 → true = 1
[Link](null + 1); // ?
✅ 1 → null = 0
[Link](undefined + 1); // ?
✅ NaN
🧠 Simple Rule
🔥 5. Truthy vs Falsy
false
0
"" (empty string)
null
undefined
NaN
⚙️ Example
if ("hello") {
[Link]("yes");
}
✅ Output:
yes
if (0) {
[Link]("no");
}
👉 No output
⚡ Shortcut
“JavaScript performs implicit type coercion in loose comparisons and operations, where
primitives are copied by value and objects by reference, with truthy and falsy values
influencing conditional evaluation.”
🧠 Core Idea
👉 Instead of writing same code again → you wrap it in a function and reuse.
⚙️ Basic Example
function greet() {
[Link]("Hello");
}
greet();
✅ Output
Hello
🧠 What’s happening?
function greet(name) {
[Link]("Hello " + name);
}
greet("Vamshi");
✅ Output
Hello Vamshi
Reusability
Cleaner code
Easy debugging
// 1. Function Declaration
function a() {}
// 2. Function Expression
const b = function() {};
// 3. Arrow Function
const c = () => {};
⚡ Interview One-Liner
“A function is a reusable block of code that can take inputs, process them, and return an
output.”
🧠 Core Idea
👉 Think:
⚙️ Basic Example
function sayBye() {
[Link]("Bye");
}
greet("Vamshi", sayBye);
✅ Output
Hi Vamshi
Bye
🧠 What’s happening?
✅ Output
Hi JS
Done
setTimeout(function() {
[Link]("Executed after 1 sec");
}, 1000);
👉 Here:
function is passed
⚠️ Important Concept
⚡ Interview One-Liner
🧠 Core Idea
function add(x, y) {
return x + y;
}
[Link](operate(2, 3, add));
✅ Output
🧠 What’s happening?
Calls it → fn(a, b)
Returns result
function outer() {
return function() {
[Link]("Hello");
};
}
const fn = outer();
fn();
✅ Output
Hello
🧠 What’s happening?
⚡ Real-world Examples
🧠 Why important?
Used everywhere:
o event handlers
o async code
⚡ Interview One-Liner
🔥 4. What is a Closure?
🧠 Core Idea
A closure is when a function remembers variables from its outer scope even after the outer
function has finished execution.
👉 Think:
function outer() {
let count = 0;
const fn = outer();
[Link](fn()); // ?
[Link](fn()); // ?
✅ Output
1
2
🧠 What’s happening?
3. outer() is finished ❗
BUT count is not destroyed
🧠 Mental Model
inner function
↓
remembers → count (from outer)
⚡ Why it works
Because of:
👉 Lexical scope (function remembers where it was created)
function createCounter() {
let count = 0;
return {
inc: () => ++count,
dec: () => --count
};
}
const c = createCounter();
[Link]([Link]()); // 1
[Link]([Link]()); // 2
[Link]([Link]()); // 1
function secret() {
let password = "1234";
return function() {
return password;
};
}
⚡ Killer Interview Line“A closure is a function that retains access to variables from its
lexical scope even after the outer function has executed.”
What is IIFE?
🧠 Core Idea
⚙️ Basic Example
(function() {
[Link]("Hello");
})();
✅ Output
Hello
🧠 What’s happening?
⚙️ With Parameters
(function(name) {
[Link]("Hello " + name);
})("Vamshi");
✅ Output
Hello Vamshi
⚡ Why use IIFE?
(function() {
let x = 10;
})();
[Link](x); // ❌ error
👉 x is private
👉 Must wrap in ( )
❌ Wrong:
function() {}();
✅ Correct:
(function() {})();
⚡ Interview One-Liner
“An IIFE is a function expression that executes immediately after it is defined, used to create
a private scope.”
🧠 Core Difference
⚙️ Example
const obj = {
name: "JS",
normal: function() {
[Link]([Link]);
},
arrow: () => {
[Link]([Link]);
}
};
[Link](); // ?
[Link](); // ?
✅ Output
JS
undefined
🧠 Why?
🔹 Normal Function
👉 so → [Link] = "JS"
🔹 Arrow Function
⚙️ Another Example
function test() {
[Link](this);
}
test();
⚡ Syntax Difference
// Normal
function add(a, b) {
return a + b;
}
// Arrow
const add = (a, b) => a + b;
⚡ Key Differences
👉 Use arrow:
short functions
callbacks
React
👉 Use normal:
object methods
⚡ Interview One-Liner
“Arrow functions don’t have their own this; they inherit it from the surrounding lexical
scope, unlike normal functions where this depends on how the function is called.”
🔥 7. What is Currying?
🧠 Core Idea
Currying = converting a function with multiple arguments into a series of functions with
one argument each
👉 Instead of:
add(2, 3)
👉 You write:
add(2)(3)
⚙️ Basic Example
function add(a) {
return function(b) {
return a + b;
};
}
[Link](add(2)(3));
✅ Output
5
🧠 What’s happening?
3. Final result → 2 + 3 = 5
[Link](add(5)(2));
✅ Output
✅ 1. Reusability
[Link](add10(5)); // 15
[Link](add10(20)); // 30
Used in:
React
functional programming
⚡ Interview Insight
“Currying transforms a function with multiple parameters into a sequence of functions each
taking a single argument.”
🔥 8. What is Memoization?
🧠 Core Idea
👉 Think:
function square(n) {
[Link]("calculating...");
return n * n;
}
square(4);
square(4);
❗ Output
calculating...
16
calculating...
16
⚙️ With Memoization
function memo(fn) {
let cache = {};
return function(n) {
if (cache[n]) {
return cache[n];
}
[Link](fastSquare(4));
[Link](fastSquare(4));
✅ Output
calculating...
16
16
🧠 What’s happening?
🧠 Memory View
cache = {
4: 16
}
⚡ Why important?
Improves performance
Used in:
o heavy calculations
o APIs
o React optimization
if (cache[n])
👉 fails for 0
Better:
if (n in cache)
⚡ Interview One-Liner
🔥 9. Debouncing vs Throttling
🧠 Core Idea
Both control how often a function runs (especially in events like typing, scrolling)
⚙️ 1. Debouncing
🧠 Concept
return function() {
clearTimeout(timer);
timer = setTimeout(fn, delay);
};
}
🧠 How it works
🎯 Real Example
Form validation
⚡ Behavior
⚙️ 2. Throttling
🧠 Concept
👉 Run function at fixed intervals, no matter how many times event occurs
⚙️ Example
return function() {
if (!flag) return;
fn();
flag = false;
setTimeout(() => {
flag = true;
}, limit);
};
}
🧠 How it works
🎯 Real Example
Scroll events
Resize events
⚡ Behavior
🔥 Key Difference
⚡ Simple Analogy
⚡ Interview One-Liner
“Debouncing delays execution until after inactivity, while throttling limits execution to fixed
intervals during continuous events.”
🔥10. What is Lexical Scope?
🧠 Core Idea
Lexical Scope =
scope is decided by where variables are written in code (not how functions are called)
⚙️ Simple Example
let a = 10;
function outer() {
let b = 20;
function inner() {
[Link](a, b);
}
inner();
}
outer();
✅ Output
10 20
🧠 Why?
1. inside inner
2. inside outer
3. global scope
⚡ Key Rule
Scope depends on WHERE function is defined,
NOT where it is called
function outer() {
let x = 10;
const fn = outer();
fn();
✅ Output
10
🧠 Why?
So it remembers x
👉 That is lexical scope → enables closure
⚠️ Trap Example
let x = 100;
function test() {
[Link](x);
}
function run() {
let x = 50;
test();
}
run();
✅ Output
100
🧠 Why?
👉 This proves:
⚡ One-Line Definition
“Lexical scope means variables are resolved based on the location where functions are
defined in the code.”
🧠 Synchronous (Sync)
⚙️ Example
[Link]("A");
[Link]("B");
[Link]("C");
✅ Output
A
B
C
🧠 Why?
JS is single-threaded
function heavy() {
for (let i = 0; i < 1e9; i++) {}
}
[Link]("Start");
heavy();
[Link]("End");
🔥 Asynchronous (Async)
⚙️ Example
[Link]("Start");
setTimeout(() => {
[Link]("Async Task");
}, 1000);
[Link]("End");
✅ Output
Start
End
Async Task
🧠 Why?
setTimeout goes to Web API
Executes later
⚡ Key Difference
⚡ Real-world Understanding
⚡ Interview One-Liner
“Synchronous code executes sequentially and blocks execution, while asynchronous code
allows non-blocking operations by deferring tasks.”
🧠 Core Idea
Event Loop = the mechanism that decides when async code should run
👉 Think:
⚙️ Key Components
[Link]("A");
setTimeout(() => {
[Link]("B");
}, 0);
[Link]("C");
✅ Output
A
C
B
🧠 Step-by-step
3. "C" → prints
o stack empty? ✅
6. "B" prints
🔄 Flow Visualization
[Link]("A");
[Link]("C");
✅ Output
A
C
B
“The event loop continuously checks the call stack and moves callbacks from task queues to
the stack when it becomes empty, enabling asynchronous execution in JavaScript.”
🧠 Core Idea
🔹 Microtask Queue
[Link]()
async/await (after await)
🔹 Macrotask Queue
setTimeout
setInterval
DOM events
⚙️ Example
[Link]("A");
[Link]("D");
✅ Output
A
D
C
B
🧠 Step-by-step
🔄 Execution Order
Call Stack (sync)
↓
Microtask Queue (Promise)
↓
Macrotask Queue (setTimeout)
⚙️ Another Example
[Link]("start");
[Link]().then(() => {
[Link]("promise1");
return [Link]();
}).then(() => [Link]("promise2"));
[Link]("end");
✅ Output
start
end
promise1
promise2
timeout
🧠 Why?
⚡ Golden Rule
⚡ Interview One-Liner
“Microtasks like Promises have higher priority and execute before macrotasks like
setTimeout once the call stack is empty.”
🧠 Core Idea
Web APIs are features provided by the browser (not JavaScript itself) that handle async
tasks.
timers
network calls
DOM events
setTimeout
setInterval
localStorage
⚙️ Example
[Link]("Start");
setTimeout(() => {
[Link]("Hello");
}, 1000);
[Link]("End");
✅ Output
Start
End
Hello
3. [Link] → runs
7. "Hello" prints
🔄 Flow
⚡ Important Insight
Single-threaded + synchronous
fetch("[Link]
.then(res => [Link]())
.then(data => [Link](data));
👉 fetch handled by Web API
👉 Response later pushed to microtask queue
⚡ Interview One-Liner
“Web APIs are browser-provided features that handle asynchronous operations like timers
and network requests outside the JavaScript engine.”
🔥 5. What is a Promise?
🧠 Core Idea
👉 Think:
⚙️ Basic Syntax
⚙️ Example
[Link](result => {
[Link](result);
});
🧠 What’s happening?
1. Promise created
3. resolve() called
⚙️ Reject Example
[Link](err => {
[Link](err);
});
✅ Output
Error occurred
⚡ Why Promises?
Before:
callback hell 😵
Now:
clean chaining 🙂
⚡ Key Features
Supports chaining
Better error handling
fetch("[Link]
.then(res => [Link]())
.then(data => [Link](data))
.catch(err => [Link](err));
⚡ Interview One-Liner
🧠 Core Idea
1. Pending
2. Fulfilled (Resolved)
3. Rejected
⚙️ 1. Pending
👉 Initial state
👉 Async task is still running
⚙️ 2. Fulfilled (Resolved)
👉 Operation completed successfully
👉 resolve() is called
⚙️ 3. Rejected
👉 Operation failed
👉 reject() is called
🔄 Lifecycle Flow
⚙️ Full Example
if (success) {
resolve("Done");
} else {
reject("Failed");
}
});
✅ Output
Done
🧠 Important Rules
resolve("A");
reject("B"); // ❌ ignored
⚡ Visual Understanding
Pending
↓
┌───────┐
↓ ↓
Success Error
⚡ Interview One-Liner
“A Promise starts in a pending state and settles into either fulfilled or rejected, and this state
cannot change once settled.”
🔥 7. Promise Chaining
🧠 Core Idea
⚙️ Basic Example
p
.then(num => {
[Link](num);
return num * 2;
})
.then(num => {
[Link](num);
return num * 2;
})
.then(num => {
[Link](num);
});
✅ Output
2
4
8
🧠 What’s happening?
fetch("[Link]
.then(res => [Link]())
.then(data => {
[Link](data);
return [Link];
})
.then(id => {
[Link]("User ID:", id);
})
.catch(err => [Link](err));
⚠️ Important Rule
❌ Wrong:
.then(num => {
num * 2; // no return
})
[Link](10)
.then(x => x * 2)
.then(x => {
throw "Error!";
})
.then(x => [Link](x))
.catch(err => [Link](err));
✅ Output
Error!
⚡ Visual Flow
🧠 Core Idea
⚙️ 1. [Link]()
🧠 Concept
Example
[Link]([
[Link](1),
[Link](2),
[Link](3)
]).then(res => [Link](res));
✅ Output
[1, 2, 3]
❌ If any fails
[Link]([
[Link](1),
[Link]("Error"),
[Link](3)
])
.catch(err => [Link](err));
Output:
Error
⚡ Summary
⚙️ 2. [Link]()
🧠 Concept
Example
[Link]([
new Promise(res => setTimeout(() => res("A"), 100)),
new Promise(res => setTimeout(() => res("B"), 50))
]).then(res => [Link](res));
✅ Output
⚡ Summary
⚙️ 3. [Link]()
🧠 Concept
Example
[Link]([
[Link]("Error1"),
[Link]("Success"),
[Link]("Another")
]).then(res => [Link](res));
✅ Output
Success
❌ If all fail
Throws AggregateError
⚡ Summary
⚙️ 4. [Link]()
🧠 Concept
Example
[Link]([
[Link]("A"),
[Link]("B")
]).then(res => [Link](res));
✅ Output
[
{ status: "fulfilled", value: "A" },
{ status: "rejected", reason: "B" }
]
⚡ Summary
Never fails
Gives full result of all promises
🔥 FINAL COMPARISON
⚡ Interview One-Liner
“[Link] waits for all to resolve, race resolves on the first settled promise, any resolves
on the first successful one, and allSettled returns results of all regardless of success or
failure.”
⚡ Real-world Insight
🧠 Core Idea
⚙️ Basic Example
Hello
🧠 Why?
return "Hello"
👉 becomes:
[Link]("Hello")
⚙️ Using await
test();
✅ Output
Done
await [Link]();
[Link](2);
}
[Link](3);
test();
[Link](4);
✅ Output
3
1
4
2
🧠 Why?
1. Sync runs → 3
2. test() starts → 1
4. 4 runs
5. Microtask executes → 2
⚡ Key Rule
⚡ Advantages
Cleaner than .then()
Easy to read
⚠️ Important Rules
⚡ Interview One-Liner
“Async/await is syntactic sugar over promises that allows writing asynchronous code in a
synchronous style, where await pauses execution and resumes via the microtask queue.”
(try/catch vs .catch)
🧠 Core Idea
[Link]("Error happened")
.then(res => [Link](res))
.catch(err => [Link](err));
✅ Output
Error happened
🧠 How it works
test();
✅ Output
Error!
🧠 How it works
try/catch catches it
⚙️ 3. Mixed Example
test()
.then(res => [Link](res))
.catch(err => [Link](err));
✅ Output
10
⚠️ Important Trap
test();
✅ Correct
await [Link]("Error");
⚡ Difference
⚡ Interview One-Liner
“Errors in promises are handled using .catch(), while in async/await they are handled using
try/catch, where await throws errors like synchronous code.”
🧠 Core Idea
Callback Hell = deeply nested callbacks that make code unreadable and hard to maintain
👉 Also called:
"Pyramid of Doom"
getData(function(a) {
getMoreData(a, function(b) {
getEvenMoreData(b, function(c) {
[Link](c);
});
});
});
😵 Problem
🧠 Why it happens?
✅ 1. Use Promises
getData()
.then(a => getMoreData(a))
.then(b => getEvenMoreData(b))
.then(c => [Link](c))
.catch(err => [Link](err));
🧠 Why better?
Flat structure
Easy to read
[Link](c);
} catch (err) {
[Link](err);
}
}
🧠 Why best?
Easy debugging
⚡ Visual Difference
⚡ Interview One-Liner
“Callback hell refers to deeply nested callbacks that reduce readability and maintainability,
and it can be avoided using promises or async/await for cleaner asynchronous flow.”
🔥 1. Different ways to create objects
🧠 Core Idea
const obj = {
name: "JS",
age: 10
};
[Link]([Link]);
✅ Output
JS
[Link]([Link]);
✅ Output
JS
⚙️ 3. Constructor Function
function Person(name) {
[Link] = name;
}
✅ Output
Vamshi
class Person {
constructor(name) {
[Link] = name;
}
}
✅ Output
JS
⚙️ 5. [Link]()
[Link]([Link]);
✅ Output
JS
⚡ Summary
“Objects can be created using object literals, constructors, classes, or [Link], with
literals being the most common approach.”
🔥 2. String Methods
🧠 Core Idea
⚙️ 1. length
✅ Output:
⚙️ 2. toUpperCase() / toLowerCase()
[Link]([Link]());
[Link]([Link]());
✅ Output:
HELLO
hello
⚙️ 3. includes()
let str = "javascript";
[Link]([Link]("script"));
✅ Output:
true
⚙️ 4. indexOf()
[Link]([Link]("l"));
✅ Output:
⚙️ 5. slice()
[Link]([Link](0, 4));
✅ Output:
java
⚙️ 6. substring()
[Link]([Link](1, 4));
✅ Output:
ell
⚙️ 7. replace()
let str = "hello world";
[Link]([Link]("world", "JS"));
✅ Output:
hello JS
⚙️ 8. split()
[Link]([Link](","));
✅ Output:
["a","b","c"]
⚙️ 9. trim()
[Link]([Link]());
✅ Output:
"hello"
⚙️ 10. charAt()
[Link]([Link](1));
✅ Output:
⚡ Important Insight
“String methods are built-in functions used to manipulate strings, and they return new
strings since strings are immutable.”
👉 First correction:
🔥 1. slice()
🧠 Core Idea
⚙️ String Example
[Link]([Link](0, 4));
[Link](str);
✅ Output
java
javascript
⚙️ Array Example
[Link]([Link](1,3));
[Link](arr);
✅ Output
[2,3]
[1,2,3,4]
⚡ Key Points
slice(start, end)
end is NOT included
original not changed
🔥 2. splice()
🧠 Core Idea
⚙️ Example (remove)
[Link](1,2);
[Link](arr);
✅ Output
[1,4]
⚙️ Example (add)
[Link](1,0,"X");
[Link](arr);
✅ Output
[1,"X",2,3]
⚙️ Example (replace)
[Link](1,1,"X");
[Link](arr);
✅ Output
[1,"X",3]
⚡ Key Points
🔥 FINAL DIFFERENCE
⚡ Interview One-Liner
“slice returns a shallow copy without modifying the original, while splice modifies the
original array by adding or removing elements.”
⚙️ 1. [Link]()
[Link]([Link](obj));
✅ Output:
["a","b"]
⚙️ 2. [Link]()
✅ Output:
[1,2]
⚙️ 3. [Link]()
✅ Output:
[["a",1]]
⚙️ 4. hasOwnProperty()
[Link]([Link]("a"));
✅ Output:
true
⚙️ 5. [Link]()
const a = { x:1 };
const b = { y:2 };
[Link](c);
✅ Output:
{x:1, y:2}
⚡ Important Insight
const obj = {
name: "JS",
greet: () => {
[Link]([Link]);
}
};
[Link]();
👉 Output: undefined
👉 Why:
⚡ Interview One-Liner
“Object methods are functions defined inside objects that operate on object properties
using this.”
🔥 4. What is Destructuring?
🧠 Core Idea
⚙️ 1. Array Destructuring
[Link](a, b, c);
✅ Output
10 20 30
⚡ Skip values
[Link](a, c);
✅ Output:
10 30
⚙️ 2. Object Destructuring
let obj = {
name: "JS",
age: 10
};
[Link](name, age);
✅ Output
JS 10
⚡ Rename variables
[Link](n);
✅ Output:
JS
⚡ Default values
let { city = "India" } = obj;
[Link](city);
✅ Output:
India
⚙️ 3. Nested Destructuring
let obj = {
user: {
name: "JS"
}
};
[Link](name);
✅ Output
JS
⚡ Why important?
Cleaner code
Less repetition
⚡ Before vs After
// ❌ Normal
let name = [Link];
// ✅ Destructuring
let { name } = obj;
⚡ Interview One-Liner “Destructuring is a syntax that allows extracting values from arrays
or objects into separate variables in a concise way.”
🔥 5. Spread vs Rest Operator (...)
⚙️ 1. Spread Operator
🧠 Core Idea
⚙️ Example (Array)
[Link](newArr);
✅ Output
[1,2,3,4]
⚙️ Example (Object)
[Link](newObj);
✅ Output
🧠 Why?
Copies values
⚙️ 2. Rest Operator
🧠 Core Idea
⚙️ Example (Function)
function sum(...nums) {
return nums;
}
[Link](sum(1,2,3));
✅ Output
[1,2,3]
⚙️ Example (Destructuring)
[Link](a);
[Link](rest);
✅ Output
1
[2,3,4]
🔥 KEY DIFFERENCE
⚡ Position Trick
⚠️ Common Confusion
let arr = [1,2,3];
[Link](...arr);
👉 Output:
123
⚡ Interview One-Liner
“Spread expands elements, while rest collects multiple elements into a single variable,
though both use the same ... syntax.”
🧠 Core Idea
👉 Shallow Copy
👉 Deep Copy
⚙️ 1. Shallow Copy
let obj1 = {
name: "JS",
address: { city: "BLR" }
};
[Link] = "HYD";
[Link]([Link]); // ?
✅ Output
HYD
🧠 Why?
[Link] ─┐
├── same memory
[Link] ─┘
⚙️ 2. Deep Copy
let obj1 = {
name: "JS",
address: { city: "BLR" }
};
[Link] = "HYD";
[Link]([Link]); // ?
✅ Output
BLR
🧠 Why?
No shared memory
⚠️ Important Limitation
[Link]([Link](obj))
undefined
Date
🔥 Key Difference
⚡ Interview One-Liner
“A shallow copy copies only the first level and shares nested references, while a deep copy
creates a completely independent copy of all nested structures.”
⚙️ 1. map()
🧠 Core Idea
Example
[Link](res);
✅ Output
[2,4,6]
⚙️ 2. filter()
🧠 Core Idea
Example
[Link](res);
✅ Output
[2,4]
⚙️ 3. reduce()
🧠 Core Idea
Example
[Link](sum);
✅ Output
10
⚙️ 4. find()
🧠 Core Idea
[Link](res);
✅ Output
⚙️ 5. forEach()
🧠 Core Idea
Example
✅ Output
1
2
3
🔥 Quick Comparison
⚡ Important Insight
👉 map, filter, reduce → return new array/value
👉 forEach → returns undefined
⚡ Interview One-Liner
“Array methods like map, filter, and reduce are higher-order functions used for
transformation, selection, and aggregation, while forEach is used for iteration without
returning a value.”
🧠 Core Idea
⚙️ Example
[Link](a);
[Link](b);
✅ Output
[2,4,6]
undefined
🧠 Why?
🔹 map()
👉 [2,4,6]
🔹 forEach()
👉 returns undefined
⚙️ Another Example
[Link](x => {
[Link](x * 2);
});
✅ Output
2
4
6
🔥 Key Differences
map → chainable
forEach → not chainable
⚠️ Interview Trap
👉 Output: undefined ❌
⚡ Interview One-Liner
“map returns a new transformed array, while forEach simply iterates over elements without
returning anything.”
🧠 Core Idea
👉 Not fixed
👉 Decided at runtime (how function is called)
⚙️ Example
const obj = {
name: "JS",
greet() {
[Link]([Link]);
}
};
[Link]();
✅ Output
JS
👉 this = obj
⚡ Interview One-Liner
“this refers to the object that is invoking the function, determined at runtime.”
⚙️ 1. Global Context
[Link](this);
🧠 Output
Browser → window
function test() {
[Link](this);
}
test();
🧠 Output
Browser → window
const obj = {
name: "JS",
show() {
[Link]([Link]);
}
};
[Link]();
✅ Output
JS
👉 this = object
⚙️ 4. Arrow Function
const obj = {
name: "JS",
show: () => {
[Link]([Link]);
}
};
[Link]();
❌ Output
undefined
🧠 Why?
⚡ Summary
⚙️ 1. call()
function greet(age) {
[Link]([Link], age);
}
[Link](obj, 25);
✅ Output
JS 25
⚙️ 2. apply()
👉 Same as call
👉 Arguments passed as array
[Link](obj, [25]);
✅ Output
JS 25
⚙️ 3. bind()
✅ Output
JS 25
🔥 Key Differences
⚡ Interview One-Liner
“call and apply invoke functions immediately with a specified this, while bind returns a new
function with this permanently set.”
⚡ Memory Trick
🧠 Core Idea
Prototype = an object from which other objects inherit properties and methods
⚙️ Example
function Person(name) {
[Link] = name;
}
[Link] = function() {
[Link]("Hello " + [Link]);
};
✅ Output
Hello JS
🧠 Why?
It is inside prototype
⚡ Key Idea
⚡ Interview One-Liner
🔥 2. __proto__ vs prototype
🧠 Difference
⚙️ Example
function A() {}
const obj = new A();
✅ Output
true
🧠 Meaning
⚡ Simple View
⚡ Interview One-Liner
🔥 3. Prototypal Inheritance
🧠 Core Idea
⚙️ Example
const parent = {
greet() {
[Link]("Hello");
}
};
✅ Output
Hello
🧠 Why?
⚡ Prototype Chain
⚡ Interview One-Liner
“Prototypal inheritance allows objects to inherit properties from other objects through the
prototype chain.”
🔥 4. Constructor Functions
🧠 Core Idea
⚙️ Example
function Person(name) {
[Link] = name;
}
[Link]([Link], [Link]);
✅ Output
AB
⚡ Interview One-Liner
“Constructor functions are used to create multiple object instances using the new keyword.”
🔥 5. Classes in JavaScript
🧠 Core Idea
⚙️ Example
class Person {
constructor(name) {
[Link] = name;
}
greet() {
[Link]("Hi " + [Link]);
}
}
✅ Output
Hi JS
🧠 Important Truth
⚙️ Inheritance
class A {
greet() {
[Link]("Hello");
}
}
class B extends A {}
✅ Output
Hello
⚡ Interview One-Liner
“Classes in JavaScript provide a cleaner syntax for creating objects and handling inheritance,
but they are internally based on prototypes.”
⚡ FINAL SUMMARY
🔥 1. What is DOM?
🧠 Core Idea
DOM (Document Object Model) =
representation of HTML as a tree of objects
⚙️ Example
HTML:
<body>
<h1>Hello</h1>
</body>
🧠 DOM Structure
document
└── body
└── h1
⚡ Why DOM?
👉 JS can:
read HTML
change content
handle events
⚙️ Example
[Link]("h1").textContent = "Hi";
👉 Changes UI dynamically
⚡ Interview One-Liner
“The DOM is a tree-like representation of HTML that allows JavaScript to interact with and
manipulate web page elements.”
🔥 2. DOM Manipulation Methods
⚙️ 1. Select Elements
[Link]("id");
[Link]("cls");
[Link](".cls");
[Link]("div");
⚙️ 2. Change Content
[Link] = "Hello";
[Link] = "<b>Hi</b>";
⚙️ 3. Change Style
[Link] = "red";
[Link](div);
[Link]();
⚙️ 5. Events
[Link]("click", () => {
[Link]("Clicked");
});
⚡ Interview One-Liner
“DOM manipulation involves selecting elements and dynamically modifying their content,
structure, and styles using JavaScript.”
🔥 3. Event Bubbling vs Capturing
🧠 Core Idea
⚙️ Example Structure
<div>
<button>Click</button>
</div>
⚙️ Bubbling (default)
👉 Event goes:
⚙️ Example
button
div
⚙️ Capturing
👉 Event goes:
⚙️ Enable capturing
⚡ Interview One-Liner
“Event bubbling propagates events from child to parent, while capturing propagates from
parent to child.”
🔥 4. Event Delegation
🧠 Core Idea
⚙️ Example
🧠 Why?
Improves performance
⚙️ HTML
<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
</ul>
👉 Clicking any li → handled by parent
⚡ Benefits
Less code
Better performance
Handles dynamic elements
⚡ Interview One-Liner
“Event delegation is a technique where a parent element handles events for its child
elements using event bubbling.”
⚡ FINAL SUMMARY
🧠 Core Idea
lifetime
size
usage
⚙️ 1. localStorage
🧠 Concept
👉 Stores data permanently (until manually deleted)
Example
[Link]("name", "JS");
[Link]([Link]("name"));
✅ Output
JS
⚡ Features
No expiry
~5MB storage
Data persists after refresh/browser close
⚙️ 2. sessionStorage
🧠 Concept
Example
[Link]("user", "A");
⚡ Features
⚙️ 3. Cookies
🧠 Concept
[Link] = "name=JS";
⚡ Features
~4KB size
Has expiry
Sent to server automatically
🔥 KEY DIFFERENCE
localStorage → permanent
sessionStorage→ session only
cookies → small + server communication
⚡ Comparison Table
Server sent ❌ ❌ ✅
⚡ Interview One-Liner
“localStorage stores persistent data, sessionStorage stores data per session, and cookies
store small data that is sent to the server with each request.”
✅ 1. for...in vs for...of
🧠 Core Difference
⚙️ Example
✅ Output
0
1
2
✅ Output
a
b
c
⚠️ Important
⚡ Interview Line
“for...in iterates over keys, while for...of iterates over values of iterable objects.”
🧠 Core Idea
⚙️ Example
[Link]([Link]());
[Link]([Link]());
✅ Output
🧠 Meaning
🔥 ⚡ Functions (Advanced)
✅ 3. Pure Functions
🧠 Core Idea
✔ predictable ✔ safe
❌ 4. Impure Functions
🧠 Core Idea
let x = 10;
function add(a) {
return a + x;
}
⚡ Difference
Pure → predictable
Impure → unpredictable
✅ 5. Function Composition
🧠 Core Idea
[Link](result);
✅ Output
12
👉 Output flows:
add → multiply
🧠 Core Idea
⚙️ Example
function* gen() {
yield 1;
yield 2;
}
const g = gen();
[Link]([Link]());
[Link]([Link]());
✅ Output
🧠 Why?
next() resumes
✅ 7. Lexical Environment
🧠 Core Idea
let a = 10;
function test() {
[Link](a);
}
⚡ Interview Line
✅ 8. Variable Environment
🧠 Core Idea
var a = 10;
⚡ Key Difference
Fast
Fixed size
let a = 10;
🧠 Heap
Stores objects
Dynamic size
⚡ Difference
🧠 Core Idea
⚙️ Example
obj = null;