0% found this document useful (0 votes)
4 views118 pages

Javascript Explain

JavaScript is a high-level, interpreted, single-threaded programming language primarily used for web interactivity, characterized by dynamic typing, event-driven architecture, and prototype-based inheritance. It operates within execution contexts that manage memory allocation and execution phases, utilizing a call stack to track function execution. Key differences between variable declarations (var, let, const) include scope, hoisting behavior, and re-assignment capabilities, with hoisting and the temporal dead zone being crucial concepts for understanding variable accessibility.

Uploaded by

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

Javascript Explain

JavaScript is a high-level, interpreted, single-threaded programming language primarily used for web interactivity, characterized by dynamic typing, event-driven architecture, and prototype-based inheritance. It operates within execution contexts that manage memory allocation and execution phases, utilizing a call stack to track function execution. Key differences between variable declarations (var, let, const) include scope, hoisting behavior, and re-assignment capabilities, with hoisting and the temporal dead zone being crucial concepts for understanding variable accessibility.

Uploaded by

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

🔥 Q1: What is JavaScript? How is it different from other languages?

🧠 What is JavaScript?

JavaScript is a high-level, interpreted, single-threaded programming language mainly used


to make web pages interactive.

👉 In simple terms:

HTML = structure
CSS = design
JavaScript = behavior (logic + interaction)

⚙️ Core Nature of JavaScript

 Interpreted → runs line-by-line (no compile step like C++)

 Single-threaded → one task at a time (but async tricks make it powerful)

 Event-driven → reacts to user actions (clicks, inputs)

 Dynamically typed → no need to declare types

 Prototype-based → inheritance works via prototypes, not classes (originally)

⚡ What makes JavaScript different?

1. Dynamic Typing

let x = 10;
x = "hello";

👉 Type can change anytime (not allowed in Java)

2. Runs in Browser (unique power)

👉 JS can directly control:

 DOM (HTML elements)

 User events

 UI updates

Other languages → need frameworks/tools


3. Asynchronous by Design

setTimeout(() => [Link]("Hi"), 1000);

👉 Can handle delays, APIs without blocking

4. First-Class Functions

function greet() {}

👉 Functions behave like variables:

 pass as argument

 return from function

5. Prototype-based (not classical OOP)

👉 Objects inherit from other objects directly

⚡ Interview Killer Summary (say this)

“JavaScript is a single-threaded, dynamically typed, event-driven language designed for the


browser, with first-class functions and asynchronous capabilities that differentiate it from
traditionally compiled and statically typed languages.”

When you’re ready → ask next:

👉 Execution Context

nxt

Good. Stay sharp.

🔥 Q2: What is Execution Context?


🧠 Core Idea

Execution Context = the environment where JavaScript code runs

👉 Think:

“JS needs a box to execute code — that box is execution context”

⚙️ Types of Execution Context

1. Global Execution Context (GEC)

 Created once when program starts

 Represents entire file

[Link]("Hello");

👉 This runs inside GEC

2. Function Execution Context (FEC)

 Created every time a function is called

function test() {
[Link]("Hi");
}
test();

👉 Calling test() creates a new execution context

🧠 What’s inside Execution Context?

Each context has 2 phases:

🔹 1. Memory Creation Phase (Hoisting phase)

JS scans code and allocates memory:

 Variables → undefined

 Functions → full definition

Example:
[Link](a);
var a = 10;

Internally:

var a = undefined;
[Link](a);
a = 10;

🔹 2. Execution Phase

 Code runs line by line

 Values get assigned

 Functions execute

⚡ Visual Flow

Global Execution Context



Call function → New Execution Context

Finish → removed from stack

🧠 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

 foo() called → new FEC

4. Inside FEC:

 b = undefined → then 20

5. FEC destroyed → back to GEC

⚡ Killer Interview Line

“Execution context is the environment created by JavaScript to execute code, consisting of


memory allocation and execution phases, managed via the call stack.”

Next → Call Stack (this connects everything)

nxt

Good. Now we connect execution → real runtime behavior.

🔥 Q3: How does the Call Stack work?

🧠 Core Idea

Call Stack = a stack (LIFO) that tracks execution contexts

👉 Think:

“Which function is currently running, and what should run next”

⚙️ How it works (simple)

 JS is single-threaded → one task at a time

 So it uses a stack to manage execution


👉 Rule:

Last In → First Out (LIFO)

🧠 Basic Example

function one() {
two();
}

function two() {
[Link]("Hello");
}

one();

🔍 Step-by-step

1. Global Execution Context pushed

2. one() called → push one

3. Inside one() → call two() → push two

4. two() executes → logs "Hello"

5. two() finished → popped

6. one() finished → popped

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

👉 If stack is busy → everything else waits

💣 Stack Overflow (important)

function test() {
test();
}
test();

❌ Infinite recursion → stack keeps growing → crash

👉 Error: Maximum call stack exceeded

🔄 Async Twist (important connection)

[Link]("A");

setTimeout(() => {
[Link]("B");
}, 0);

[Link]("C");

Output:

A
C
B

Why?

 setTimeout does NOT go to stack directly

 Goes to Web API → callback queue

 Stack finishes → then pushed later

⚡ Killer Interview Line

“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

Good. This is where most candidates collapse. Stay precise.

🔥 Q4: What is Hoisting?

🧠 Core Idea

Hoisting = JavaScript moves declarations to the top of their scope before execution

👉 Not physically moving code


👉 Happens during memory creation phase

⚙️ What gets hoisted?

Type Behavior

var hoisted → initialized as undefined

let/const hoisted → NOT initialized (TDZ)

function fully hoisted (can call before declaration)

🧠 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

 Function is fully hoisted → available before declaration

🧠 Example 3 (let / const)

[Link](b);
let b = 5;

❌ Output

ReferenceError

🧠 Why

 Hoisted but not initialized

 Stays in Temporal Dead Zone

⚡ Key Difference (Interview Gold)

var → hoisted + initialized (safe access: undefined)


let/const → hoisted but uninitialized (TDZ → error)
🧠 Mental Model

During memory phase:

var a → undefined
let b → TDZ
function → full function stored

⚡ Killer Interview Line

“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.”

Next → Temporal Dead Zone (deep clarity of let/const)

nxt

Good. This is the real understanding behind let and const.

🔥 Q5: What is Temporal Dead Zone (TDZ)?

🧠 Core Idea

Temporal Dead Zone =


the time between variable hoisting and its initialization where you cannot access it

👉 Applies only to: let and const

⚙️ Simple Example

[Link](a);
let a = 10;

❌ Output

ReferenceError: Cannot access 'a' before initialization


🧠 Why this happens

Behind the scenes:

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

 Inside function → new x created

 That x is in TDZ until initialized

 [Link](x) hits TDZ → error


⚡ Key Difference vs var

[Link](a); // undefined
var a = 10;

✔ works because:

 var → initialized as undefined

⚡ Why TDZ exists (important insight)

👉 Prevents bugs from using variables before assignment


👉 Forces cleaner, predictable code

⚡ Killer Interview Line

“Temporal Dead Zone is the phase between hoisting and initialization


of let and const variables where accessing them throws a ReferenceError.”

Next → var vs let vs const (complete comparison — very frequently asked)

nxt

Good. This is a top 3 most-asked question. Answer must be sharp.

🔥 Q6: Difference between var, let, const

🧠 Core Idea

All three are used to declare variables, but differ in:

 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

 var → function scoped

 let, const → block scoped

⚙️ 2. Hoisting Behavior

[Link](a); // undefined
var a = 10;

[Link](b); // ❌ ReferenceError
let b = 20;

🧠 Why

 var → hoisted + initialized

 let/const → hoisted but in TDZ

⚙️ 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

⚙️ 5. Initialization Rule (const)

const a; // ❌ error
const b = 10; // ✅

👉 const must be initialized at declaration

⚙️ 6. Object Behavior (tricky)

const obj = { name: "JS" };


[Link] = "React"; // ✅ allowed

🧠 Why

 const locks reference, not internal values

⚡ Clean Comparison Table

Feature var let const

Scope Function Block Block

Hoisting Yes (undefined) Yes (TDZ) Yes (TDZ)

Re-declare ✅ ❌ ❌

Re-assign ✅ ✅ ❌
Feature var let const

Init required ❌ ❌ ✅

⚡ Killer Interview Line

“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.”

⚡ Real-world Insight (this impresses)

👉 Modern JS rule:

 Use const by default

 Use let if value changes

 Avoid var

Next → Scope (global, function, block) — ties everything together

explain three only

Good. Strip it down to pure clarity.

🔥 var vs let vs const (only essentials)

⚙️ 1. var

🧠 Behavior

 Function scoped

 Hoisted → initialized as undefined


 Can re-declare & re-assign

var a = 10;
var a = 20; // ✅
a = 30; // ✅

⚠️ Problem

Leaks outside block:

if (true) {
var x = 10;
}
[Link](x); // ✅ 10 (unexpected)

⚙️ 2. let

🧠 Behavior

 Block scoped

 Hoisted but in TDZ

 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

 Hoisted but in TDZ

 Cannot re-declare
 Cannot re-assign

const a = 10;
// a = 20 ❌

⚠️ Important twist

const obj = { name: "JS" };


[Link] = "React"; // ✅ allowed

👉 Only reference is fixed, not value

⚡ Ultra Short Difference

var → function scope, flexible, unsafe


let → block scope, change allowed
const→ block scope, fixed reference

⚡ Interview One-Liner

“var is function-scoped and mutable, let is block-scoped with reassignment allowed,


and const is block-scoped with fixed reference.”

Next → Scope (this will connect everything you learned so far)

nxt

Good. This ties everything together.

🔥 Q7: What is Scope? (global, function, block)

🧠 Core Idea

Scope = where a variable is accessible in your code

👉 Think:
“Where can I use this variable?”

⚙️ 1. Global Scope

 Declared outside all functions

 Accessible everywhere

let a = 10;

function test() {
[Link](a);
}

test(); // 10
[Link](a); // 10

🧠 Insight

 Lives in global execution context

 Avoid too many globals (can cause conflicts)

⚙️ 2. Function Scope

 Variables declared inside a function

 Accessible only inside that function

function test() {
let x = 20;
[Link](x); // 20
}

test();
[Link](x); // ❌ ReferenceError

🧠 Insight

 Each function creates its own private scope

⚙️ 3. Block Scope

 Variables inside {} (if, loop, etc.)


 Only for let and const

if (true) {
let a = 10;
const b = 20;
}

[Link](a); // ❌
[Link](b); // ❌

⚠️ Important Trap (var)

if (true) {
var x = 10;
}
[Link](x); // ✅ 10

👉 var ignores block scope → behaves like function scope

🔄 Scope Chain (important)

let a = 10;

function outer() {
function inner() {
[Link](a);
}
inner();
}
outer();

🧠 Why it works

 JS looks:

1. inside function

2. then outer scope

3. then global

👉 This is scope chain


⚡ Visual

Inner → Outer → Global

⚡ Killer Interview Line

“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.”

🔥 Q8: Primitive vs Reference (Non-Primitive) Data Types

🧠 1. Primitive Data Types

👉 Store actual value directly

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

 a and b store separate values

 Changing b does NOT affect a

👉 This is pass by value

🧠 Memory View

a → 10
b → 10 (copy)

🧠 2. Reference (Non-Primitive)

👉 Store reference (address), not actual value

Types:

 Object

 Array

 Function

⚙️ Example

let obj1 = { name: "JS" };


let obj2 = obj1;

[Link] = "React";

[Link]([Link]); // ?

✅ Output

React

🧠 Why

 Both variables point to same memory


 Changing one → affects other

👉 This is pass by reference

🧠 Memory View

obj1 ─┐
├──> { name: "JS" }
obj2 ─┘

⚡ Key Difference

Primitive → copy value


Reference → copy address

⚠️ Common Trap

let a = [1,2];
let b = [1,2];

[Link](a === b);

✅ Output

false

🧠 Why

 Different references (different memory)

⚡ Interview Killer Line

“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.”

🔥 9. Pass by Value vs Pass by Reference

🧠 Pass by Value (Primitive)

let a = 10;
let b = a;
b = 20;

[Link](a); // ?
[Link](b); // ?

✅ Output:

10
20

👉 Why:

 Copy of value is created

 a and b are independent

🧠 Pass by Reference (Objects)

let obj1 = { name: "JS" };


let obj2 = obj1;

[Link] = "React";

[Link]([Link]); // ?

✅ Output:

React

👉 Why:

 Both point to same memory

 Change via one → affects both

🔥 2. typeof null Bug

[Link](typeof null);

✅ Output:

"object"

👉 Why:

 Historical JS bug
 null is primitive but reported as "object"

👉 Interview line:

“It’s a legacy bug in JavaScript’s type system.”

🔥 3. == vs ===

[Link](5 == "5");
[Link](5 === "5");

✅ Output:

true
false

🧠 Difference

 == → compares after type conversion

 === → compares type + value

👉 Rule:

== → dangerous
=== → safe

🔥 4. Type Coercion Rules

👉 JS automatically converts types when needed

⚙️ Examples

[Link]("5" + 2); // ?

✅ "52" → string wins

[Link]("5" - 2); // ?

✅ 3 → numeric conversion
[Link](true + 1); // ?

✅ 2 → true = 1

[Link](null + 1); // ?

✅ 1 → null = 0

[Link](undefined + 1); // ?

✅ NaN

🧠 Simple Rule

+ → string concat if string present


-,*,/ → convert to number

🔥 5. Truthy vs Falsy

❌ Falsy Values (VERY IMPORTANT)

false
0
"" (empty string)
null
undefined
NaN

✅ Everything else → Truthy

⚙️ Example

if ("hello") {
[Link]("yes");
}

✅ Output:

yes
if (0) {
[Link]("no");
}

👉 No output

⚡ Shortcut

Falsy → empty / zero / nothing


Truthy → everything else

⚡ Final Interview Power Line

“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.”

🔥 1. What are Functions in JavaScript?

🧠 Core Idea

A function is a block of reusable code that performs a specific task.

👉 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?

1. You define a function → greet

2. You call/invoke it → greet()

3. Code inside runs

⚙️ Function with Parameters

function greet(name) {
[Link]("Hello " + name);
}

greet("Vamshi");

✅ Output

Hello Vamshi

🧠 Why this matters

 Reusability

 Cleaner code

 Easy debugging

 Core of everything (callbacks, closures, async)

⚡ Types (quick awareness)

// 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.”

🔥 2. What is a Callback Function?

🧠 Core Idea

A callback is a function passed as an argument to another function, and executed later.

👉 Think:

“I’ll give you a function — you run it when needed”

⚙️ Basic Example

function greet(name, callback) {


[Link]("Hi " + name);
callback();
}

function sayBye() {
[Link]("Bye");
}

greet("Vamshi", sayBye);

✅ Output

Hi Vamshi
Bye

🧠 What’s happening?

1. greet receives a function (sayBye)

2. After printing "Hi Vamshi"

3. It calls the callback → callback()

⚙️ Inline Callback (common in interviews)


greet("JS", function() {
[Link]("Done");
});

✅ Output

Hi JS
Done

⚡ Real-world Example (Async)

setTimeout(function() {
[Link]("Executed after 1 sec");
}, 1000);

👉 Here:

 function is passed

 executed later → async behavior

🧠 Why callbacks exist

 Handle async operations

 Make functions flexible

 Used everywhere (APIs, events, timers)

⚠️ Important Concept

👉 Callback runs only when called

⚡ Interview One-Liner

“A callback function is a function passed as an argument to another function, which is


executed later inside that function.”

🔥 3. What is a Higher-Order Function?

🧠 Core Idea

A higher-order function is a function that:


👉 either takes another function as argument
👉 or returns a function

⚙️ Example 1 — Takes function as argument

function operate(a, b, fn) {


return fn(a, b);
}

function add(x, y) {
return x + y;
}

[Link](operate(2, 3, add));

✅ Output

🧠 What’s happening?

 operate receives a function (add)

 Calls it → fn(a, b)

 Returns result

👉 So operate = higher-order function

⚙️ Example 2 — Returns a function

function outer() {
return function() {
[Link]("Hello");
};
}

const fn = outer();
fn();

✅ Output
Hello

🧠 What’s happening?

 outer() returns a function

 That returned function is executed later

⚡ Real-world Examples

[1,2,3].map(x => x * 2);

👉 map is a higher-order function


👉 because it takes a function as input

🧠 Why important?

 Used everywhere:

o map, filter, reduce

o event handlers

o async code

⚡ Interview One-Liner

“A higher-order function is a function that either accepts another function as an argument


or returns a function.”

🔥 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 carries its memory with it”


⚙️ Basic Example

function outer() {
let count = 0;

return function inner() {


count++;
return count;
};
}

const fn = outer();

[Link](fn()); // ?
[Link](fn()); // ?

✅ Output

1
2

🧠 What’s happening?

1. outer() runs → creates count = 0

2. Returns inner function

3. outer() is finished ❗
BUT count is not destroyed

4. inner() still remembers count

👉 That memory = closure

🧠 Mental Model

inner function

remembers → count (from outer)

⚡ Why it works
Because of:
👉 Lexical scope (function remembers where it was created)

⚙️ Real Use Case 1 — Counter

function createCounter() {
let count = 0;

return {
inc: () => ++count,
dec: () => --count
};
}

const c = createCounter();

[Link]([Link]()); // 1
[Link]([Link]()); // 2
[Link]([Link]()); // 1

⚙️ Real Use Case 2 — Data Privacy

function secret() {
let password = "1234";

return function() {
return password;
};
}

const getPass = secret();


[Link](getPass());

👉 password is private (cannot access directly)

⚠️ Common Interview Trap

for (var i = 0; i < 3; i++) {


setTimeout(() => [Link](i), 0);
}
👉 Output: 3 3 3
👉 Because closure shares same i

⚡ 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

IIFE = Immediately Invoked Function Expression

👉 A function that runs immediately after it is defined

⚙️ Basic Example

(function() {
[Link]("Hello");
})();

✅ Output

Hello

🧠 What’s happening?

 function() {} → function defined

 ( ) at end → immediately called

👉 No need to call separately

⚙️ With Parameters

(function(name) {
[Link]("Hello " + name);
})("Vamshi");

✅ Output

Hello Vamshi
⚡ Why use IIFE?

1. Avoid global variables

(function() {
let x = 10;
})();

[Link](x); // ❌ error

👉 x is private

2. Create private scope

👉 Before let/const, this was used heavily

⚠️ Important Syntax Trick

👉 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.”

🔥 6. Arrow Function vs Normal Function

🧠 Core Difference

👉 The biggest difference is this behavior

⚙️ Example
const obj = {
name: "JS",

normal: function() {
[Link]([Link]);
},

arrow: () => {
[Link]([Link]);
}
};

[Link](); // ?
[Link](); // ?

✅ Output

JS
undefined

🧠 Why?

🔹 Normal Function

 this depends on how function is called

 Here → called via obj → this = obj

👉 so → [Link] = "JS"

🔹 Arrow Function

 ❌ does NOT have its own this

 ✅ takes this from outer scope

👉 outer scope = global → no name → undefined

⚙️ Another Example
function test() {
[Link](this);
}
test();

👉 Normal function → this = global (or undefined in strict mode)

const test = () => {


[Link](this);
};
test();

👉 Arrow → inherits from outer scope

⚡ Syntax Difference

// Normal
function add(a, b) {
return a + b;
}

// Arrow
const add = (a, b) => a + b;

⚡ Key Differences

Feature Normal Function Arrow Function

this dynamic lexical (fixed)

arguments available not available

constructor can use cannot use

syntax longer shorter

⚡ When to use what?

👉 Use arrow:

 short functions
 callbacks

 React

👉 Use normal:

 object methods

 when this is needed

⚡ 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?

1. add(2) runs → returns a function

2. That function gets b = 3

3. Final result → 2 + 3 = 5

⚙️ Arrow Version (clean)

const add = a => b => a + b;

[Link](add(5)(2));

✅ Output

🧠 Why use Currying?

✅ 1. Reusability

const add10 = add(10);

[Link](add10(5)); // 15
[Link](add10(20)); // 30

👉 You fixed one value → reuse easily

✅ 2. Cleaner functional code

Used in:

 React

 functional programming

⚡ Interview Insight

👉 Currying = function customization


⚡ One-line Definition

“Currying transforms a function with multiple parameters into a sequence of functions each
taking a single argument.”

🔥 8. What is Memoization?

🧠 Core Idea

Memoization = store (cache) function results so repeated calls don’t recompute

👉 Think:

“If I already solved it once, don’t solve again”

⚙️ Problem Without Memoization

function square(n) {
[Link]("calculating...");
return n * n;
}

square(4);
square(4);

❗ Output

calculating...
16
calculating...
16

👉 Same work repeated → inefficient

⚙️ With Memoization

function memo(fn) {
let cache = {};

return function(n) {
if (cache[n]) {
return cache[n];
}

let result = fn(n);


cache[n] = result;
return result;
};
}

const fastSquare = memo(function(n) {


[Link]("calculating...");
return n * n;
});

[Link](fastSquare(4));
[Link](fastSquare(4));

✅ Output

calculating...
16
16

🧠 What’s happening?

1. First call → calculates + stores in cache

2. Second call → returns from cache


👉 No recalculation

🧠 Memory View

cache = {
4: 16
}

⚡ Why important?

 Improves performance

 Used in:
o heavy calculations

o APIs

o React optimization

⚠️ Small Interview Trap

if (cache[n])

👉 fails for 0

Better:

if (n in cache)

⚡ Interview One-Liner

“Memoization is an optimization technique where function results are cached to avoid


repeated computations.”

🔥 9. Debouncing vs Throttling

🧠 Core Idea

Both control how often a function runs (especially in events like typing, scrolling)

⚙️ 1. Debouncing

🧠 Concept

👉 Run function only after user stops doing something

⚙️ Example (search input)

function debounce(fn, delay) {


let timer;

return function() {
clearTimeout(timer);
timer = setTimeout(fn, delay);
};
}

🧠 How it works

 User types continuously → timer keeps resetting

 Only runs after user stops typing

🎯 Real Example

 Search bar suggestions

 Form validation

⚡ Behavior

User typing → wait → run once

⚙️ 2. Throttling

🧠 Concept

👉 Run function at fixed intervals, no matter how many times event occurs

⚙️ Example

function throttle(fn, limit) {


let flag = true;

return function() {
if (!flag) return;

fn();
flag = false;

setTimeout(() => {
flag = true;
}, limit);
};
}

🧠 How it works

 First call → runs immediately

 Then blocks for some time

 After delay → allows again

🎯 Real Example

 Scroll events

 Resize events

⚡ Behavior

Run → wait → run → wait → run

🔥 Key Difference

Debounce → runs once after delay


Throttle → runs repeatedly at intervals

⚡ Simple Analogy

 Debounce = “Wait until user stops”

 Throttle = “Allow action every few seconds”

⚡ 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)

👉 “Lexical” = based on code structure (position)

⚙️ Simple Example

let a = 10;

function outer() {
let b = 20;

function inner() {
[Link](a, b);
}

inner();
}

outer();

✅ Output

10 20

🧠 Why?

When inner() runs, JS looks for variables in this order:

1. inside inner
2. inside outer
3. global scope

👉 This chain = lexical scope chain

⚡ Key Rule
Scope depends on WHERE function is defined,
NOT where it is called

⚙️ Important Example (Interview Favorite)

function outer() {
let x = 10;

return function inner() {


[Link](x);
};
}

const fn = outer();
fn();

✅ Output

10

🧠 Why?

 inner was defined inside outer

 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?

 test is defined in global scope

 So it uses global x = 100

 NOT x = 50 from run

👉 This proves:

JS does NOT care where function is called


It cares where it is defined

⚡ One-Line Definition

“Lexical scope means variables are resolved based on the location where functions are
defined in the code.”

🔥 1. Synchronous vs Asynchronous JavaScript

🧠 Synchronous (Sync)

👉 Code runs line by line, one after another


👉 Next line waits until current line finishes

⚙️ Example

[Link]("A");
[Link]("B");
[Link]("C");

✅ Output

A
B
C
🧠 Why?

 JS is single-threaded

 Executes one task at a time

❌ Problem with Sync

function heavy() {
for (let i = 0; i < 1e9; i++) {}
}

[Link]("Start");
heavy();
[Link]("End");

👉 UI freezes until loop completes ❌

🔥 Asynchronous (Async)

👉 Code can run later without blocking

⚙️ Example

[Link]("Start");

setTimeout(() => {
[Link]("Async Task");
}, 1000);

[Link]("End");

✅ Output

Start
End
Async Task

🧠 Why?
 setTimeout goes to Web API

 Doesn’t block main thread

 Executes later

⚡ Key Difference

Synchronous → blocking (waits)


Asynchronous → non-blocking (doesn’t wait)

⚡ Real-world Understanding

 Sync → like standing in queue

 Async → like ordering food + waiting aside

⚡ Interview One-Liner

“Synchronous code executes sequentially and blocks execution, while asynchronous code
allows non-blocking operations by deferring tasks.”

🔥 2. What is Event Loop?

🧠 Core Idea

Event Loop = the mechanism that decides when async code should run

👉 Think:

“Who decides when setTimeout or Promise runs?” → Event Loop

⚙️ Key Components

Call Stack ← executes code


Web APIs ← handles async (setTimeout, fetch)
Queues ← store callbacks
Event Loop ← moves tasks to stack
⚙️ Example

[Link]("A");

setTimeout(() => {
[Link]("B");
}, 0);

[Link]("C");

✅ Output

A
C
B

🧠 Step-by-step

1. "A" → goes to call stack → prints

2. setTimeout → sent to Web API

3. "C" → prints

4. After delay → callback goes to queue

5. Event loop checks:

o stack empty? ✅

o move callback to stack

6. "B" prints

🔄 Flow Visualization

Call Stack → empty



Event Loop checks

Queue → pushes callback

Web API → completes async task
⚡ Important Rule

👉 Event loop runs only when call stack is empty

⚠️ Important Upgrade (Promises)

[Link]("A");

[Link]().then(() => [Link]("B"));

[Link]("C");

✅ Output

A
C
B

👉 Promise callbacks go to microtask queue (higher priority)

⚡ Killer Interview Line

“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.”

🔥 3. Microtask vs Macrotask Queue

🧠 Core Idea

JavaScript has two types of async queues:

1. Microtask Queue (HIGH priority)


2. Macrotask Queue (LOW priority)

⚙️ What goes where?

🔹 Microtask Queue

 [Link]()
 async/await (after await)

🔹 Macrotask Queue

 setTimeout

 setInterval

 DOM events

⚙️ Example

[Link]("A");

setTimeout(() => [Link]("B"), 0);

[Link]().then(() => [Link]("C"));

[Link]("D");

✅ Output

A
D
C
B

🧠 Step-by-step

1. Sync runs first → A, D

2. Promise → goes to microtask queue

3. setTimeout → goes to macrotask queue

👉 Event loop rule:

Run ALL microtasks first → then one macrotask

🔄 Execution Order
Call Stack (sync)

Microtask Queue (Promise)

Macrotask Queue (setTimeout)

⚙️ Another Example

[Link]("start");

setTimeout(() => [Link]("timeout"), 0);

[Link]().then(() => {
[Link]("promise1");
return [Link]();
}).then(() => [Link]("promise2"));

[Link]("end");

✅ Output

start
end
promise1
promise2
timeout

🧠 Why?

 All microtasks (promise1, promise2) run first

 Then macrotask (timeout)

⚡ Golden Rule

Microtasks ALWAYS run before macrotasks

⚡ Interview One-Liner
“Microtasks like Promises have higher priority and execute before macrotasks like
setTimeout once the call stack is empty.”

🔥 4. What are Web APIs?

🧠 Core Idea

Web APIs are features provided by the browser (not JavaScript itself) that handle async
tasks.

👉 JS alone cannot do:

 timers

 network calls

 DOM events

👉 Browser gives these via Web APIs

⚙️ Common Web APIs

 setTimeout

 setInterval

 fetch (API calls)

 DOM events (click, scroll)

 localStorage

⚙️ Example

[Link]("Start");

setTimeout(() => {
[Link]("Hello");
}, 1000);

[Link]("End");
✅ Output

Start
End
Hello

🧠 What’s happening internally?

1. [Link] → Call Stack → runs

2. setTimeout → sent to Web API

3. [Link] → runs

4. Timer completes in Web API

5. Callback → goes to Macrotask Queue

6. Event Loop → moves to Call Stack

7. "Hello" prints

🔄 Flow

Call Stack → Web API → Queue → Event Loop → Call Stack

⚡ Important Insight

👉 JavaScript itself is:

Single-threaded + synchronous

👉 Async behavior comes from:

Web APIs + Event Loop

⚙️ Another Example (fetch)

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

A Promise is an object that represents the future result of an async operation

👉 Think:

“I promise to give you a result later”

⚙️ Basic Syntax

const promise = new Promise((resolve, reject) => {


resolve("Success");
});

⚙️ Example

const p = new Promise((resolve, reject) => {


setTimeout(() => {
resolve("Data received");
}, 1000);
});

[Link](result => {
[Link](result);
});

✅ Output (after 1 sec)


Data received

🧠 What’s happening?

1. Promise created

2. Async task runs (setTimeout)

3. resolve() called

4. .then() executes with result

⚙️ Reject Example

const p = new Promise((resolve, reject) => {


reject("Error occurred");
});

[Link](err => {
[Link](err);
});

✅ Output

Error occurred

⚡ Why Promises?

Before:

callback hell 😵

Now:

clean chaining 🙂

⚡ Key Features

 Handles async operations

 Avoids nested callbacks

 Supports chaining
 Better error handling

⚡ Real Example (API)

fetch("[Link]
.then(res => [Link]())
.then(data => [Link](data))
.catch(err => [Link](err));

⚡ Interview One-Liner

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


asynchronous operation.”

🔥 6. Promise States & Lifecycle

🧠 Core Idea

A Promise always exists in one of 3 states:

1. Pending
2. Fulfilled (Resolved)
3. Rejected

⚙️ 1. Pending

👉 Initial state
👉 Async task is still running

const p = new Promise((resolve, reject) => {


// still running → pending
});

⚙️ 2. Fulfilled (Resolved)
👉 Operation completed successfully
👉 resolve() is called

const p = new Promise((resolve) => {


resolve("Success");
});

⚙️ 3. Rejected

👉 Operation failed
👉 reject() is called

const p = new Promise((resolve, reject) => {


reject("Error");
});

🔄 Lifecycle Flow

Pending → Fulfilled (resolve)


→ Rejected (reject)

👉 Once changed → cannot change again

⚙️ Full Example

const p = new Promise((resolve, reject) => {


let success = true;

if (success) {
resolve("Done");
} else {
reject("Failed");
}
});

[Link](res => [Link](res))


.catch(err => [Link](err));

✅ Output
Done

🧠 Important Rules

1. Only one state change allowed

resolve("A");
reject("B"); // ❌ ignored

2. .then() → for success

3. .catch() → for error

⚡ 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

Promise chaining = executing multiple async steps in sequence using .then()

👉 Output of one step → input to next

⚙️ Basic Example

const p = new Promise((resolve) => {


resolve(2);
});

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?

1. First .then gets 2

2. Returns 4 → passed to next

3. Returns 8 → passed to next

👉 Chain flows step by step

⚙️ Real Example (API style)

fetch("[Link]
.then(res => [Link]())
.then(data => {
[Link](data);
return [Link];
})
.then(id => {
[Link]("User ID:", id);
})
.catch(err => [Link](err));

⚠️ Important Rule

👉 Always return inside .then()

❌ Wrong:

.then(num => {
num * 2; // no return
})

👉 Next .then gets undefined

⚙️ Error Handling in Chain

[Link](10)
.then(x => x * 2)
.then(x => {
throw "Error!";
})
.then(x => [Link](x))
.catch(err => [Link](err));

✅ Output

Error!

🧠 Why chaining is important?

 Avoids callback hell

 Keeps code readable

 Controls async flow

⚡ Visual Flow

Promise → then → then → then → catch


⚡ Interview One-Liner

“Promise chaining allows sequential execution of asynchronous operations by passing results


through multiple .then() handlers.”

🔥 8. [Link] vs race vs any vs allSettled

🧠 Core Idea

These are methods to handle multiple promises together

⚙️ 1. [Link]()

🧠 Concept

👉 Waits for ALL promises to succeed

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

All success → returns array


Any fail → fails immediately

⚙️ 2. [Link]()

🧠 Concept

👉 Returns first completed promise (success or fail)

Example

[Link]([
new Promise(res => setTimeout(() => res("A"), 100)),
new Promise(res => setTimeout(() => res("B"), 50))
]).then(res => [Link](res));

✅ Output

⚡ Summary

First finished wins (no matter success/fail)

⚙️ 3. [Link]()

🧠 Concept

👉 Returns first successful promise

Example

[Link]([
[Link]("Error1"),
[Link]("Success"),
[Link]("Another")
]).then(res => [Link](res));

✅ Output

Success

❌ If all fail

Throws AggregateError

⚡ Summary

First success wins


Ignores failures unless all fail

⚙️ 4. [Link]()

🧠 Concept

👉 Waits for all promises (success or fail)

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

all → all must succeed


race → first result (any)
any → first success
allSettled → all results (success + fail)

⚡ 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

 all → load multiple APIs together

 race → timeout handling

 any → fallback APIs

 allSettled → show all results

🔥 9. Async / Await (How it works internally)

🧠 Core Idea

👉 async/await is just syntactic sugar over Promises

👉 Makes async code look like synchronous code

⚙️ Basic Example

async function test() {


return "Hello";
}

test().then(res => [Link](res));


✅ Output

Hello

🧠 Why?

👉 async always returns a Promise

return "Hello"

👉 becomes:

[Link]("Hello")

⚙️ Using await

async function test() {


let res = await [Link]("Done");
[Link](res);
}

test();

✅ Output

Done

🧠 What await does

👉 Pauses function execution


👉 Waits for promise to resolve
👉 Then continues

⚙️ Internal Working (VERY IMPORTANT)

async function test() {


[Link](1);

await [Link]();

[Link](2);
}

[Link](3);
test();
[Link](4);

✅ Output

3
1
4
2

🧠 Why?

1. Sync runs → 3

2. test() starts → 1

3. await → pauses → moves rest to microtask queue

4. 4 runs

5. Microtask executes → 2

⚡ Key Rule

await splits function into two parts

⚙️ Real Example (API)

async function getData() {


let res = await fetch("[Link]
let data = await [Link]();
[Link](data);
}

👉 Looks sync but is async

⚡ Advantages
 Cleaner than .then()

 Easy to read

 Better error handling

⚠️ Important Rules

 await works only inside async

 Still uses promises internally

⚡ 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.”

🔥 10. Error Handling in Async

(try/catch vs .catch)

🧠 Core Idea

Async code can fail → you must handle errors properly.

⚙️ 1. Using .catch() (Promises style)

[Link]("Error happened")
.then(res => [Link](res))
.catch(err => [Link](err));

✅ Output

Error happened

🧠 How it works

 If any .then() fails


 Control goes to .catch()

⚙️ 2. Using try/catch (async/await style)

async function test() {


try {
let res = await [Link]("Error!");
[Link](res);
} catch (err) {
[Link](err);
}
}

test();

✅ Output

Error!

🧠 How it works

 await throws error

 try/catch catches it

⚙️ 3. Mixed Example

async function test() {


let res = await [Link](10);
return res;
}

test()
.then(res => [Link](res))
.catch(err => [Link](err));

✅ Output

10
⚠️ Important Trap

async function test() {


[Link]("Error"); // ❌ not awaited
}

test();

👉 Error NOT caught ❌

✅ Correct

await [Link]("Error");

⚡ Difference

.catch() → promise chaining style


try/catch → async/await style (cleaner)

⚡ When to use what?

 Using .then() → use .catch()

 Using async/await → use try/catch

⚡ 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.”

🔥 11. What is Callback Hell? How to avoid it?

🧠 Core Idea

Callback Hell = deeply nested callbacks that make code unreadable and hard to maintain

👉 Also called:
"Pyramid of Doom"

⚙️ Example (Callback Hell)

getData(function(a) {
getMoreData(a, function(b) {
getEvenMoreData(b, function(c) {
[Link](c);
});
});
});

😵 Problem

Code goes → right → right → right


Hard to read ❌
Hard to debug ❌
Error handling messy ❌

🧠 Why it happens?

 Using callbacks for async operations

 Each depends on previous result

🔥 How to Avoid Callback Hell

✅ 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

 Central error handling

✅ 2. Use Async/Await (BEST)

async function process() {


try {
let a = await getData();
let b = await getMoreData(a);
let c = await getEvenMoreData(b);

[Link](c);
} catch (err) {
[Link](err);
}
}

🧠 Why best?

 Looks like synchronous code

 Clean and readable

 Easy debugging

⚡ Visual Difference

Callback Hell → Pyramid


Promises → Chain
Async/Await → Straight line ✅

⚡ 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

Objects = key-value pairs

⚙️ 1. Object Literal (most common)

const obj = {
name: "JS",
age: 10
};

[Link]([Link]);

✅ Output

JS

👉 Simple, most used

⚙️ 2. Using new Object()

const obj = new Object();


[Link] = "JS";

[Link]([Link]);

✅ Output

JS

👉 Rarely used in real projects

⚙️ 3. Constructor Function

function Person(name) {
[Link] = name;
}

const p = new Person("Vamshi");


[Link]([Link]);

✅ Output

Vamshi

👉 Used before classes

⚙️ 4. Using Class (modern way)

class Person {
constructor(name) {
[Link] = name;
}
}

const p = new Person("JS");


[Link]([Link]);

✅ Output

JS

⚙️ 5. [Link]()

const obj = [Link](null);


[Link] = "JS";

[Link]([Link]);

✅ Output

JS

👉 Creates object with custom prototype

⚡ Summary

Literal → most used


Constructor/Class → structured
[Link] → advanced use
⚡ Interview One-Liner

“Objects can be created using object literals, constructors, classes, or [Link], with
literals being the most common approach.”

🔥 2. String Methods

🧠 Core Idea

String methods = built-in functions to manipulate strings

👉 Strings are immutable (original doesn’t change)

⚙️ 1. length

let str = "hello";


[Link]([Link]);

✅ Output:

⚙️ 2. toUpperCase() / toLowerCase()

let str = "hello";

[Link]([Link]());
[Link]([Link]());

✅ Output:

HELLO
hello

⚙️ 3. includes()
let str = "javascript";

[Link]([Link]("script"));

✅ Output:

true

⚙️ 4. indexOf()

let str = "hello";

[Link]([Link]("l"));

✅ Output:

👉 First occurrence index

⚙️ 5. slice()

let str = "javascript";

[Link]([Link](0, 4));

✅ Output:

java

⚙️ 6. substring()

let str = "hello";

[Link]([Link](1, 4));

✅ Output:

ell

⚙️ 7. replace()
let str = "hello world";

[Link]([Link]("world", "JS"));

✅ Output:

hello JS

⚙️ 8. split()

let str = "a,b,c";

[Link]([Link](","));

✅ Output:

["a","b","c"]

⚙️ 9. trim()

let str = " hello ";

[Link]([Link]());

✅ Output:

"hello"

⚙️ 10. charAt()

let str = "hello";

[Link]([Link](1));

✅ Output:

⚡ Important Insight

String methods return NEW string (original unchanged)


⚡ Interview One-Liner

“String methods are built-in functions used to manipulate strings, and they return new
strings since strings are immutable.”

🔥 slice vs splice (VERY IMPORTANT)

👉 First correction:

 slice → works on strings & arrays

 splice → works on arrays only (NOT strings)

🔥 1. slice()

🧠 Core Idea

👉 Extracts part of string/array


👉 Does NOT modify original

⚙️ String Example

let str = "javascript";

[Link]([Link](0, 4));
[Link](str);

✅ Output

java
javascript

⚙️ Array Example

let arr = [1,2,3,4];

[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

👉 Adds/removes elements from array


👉 Modifies original array

⚙️ Example (remove)

let arr = [1,2,3,4];

[Link](1,2);

[Link](arr);

✅ Output

[1,4]

⚙️ Example (add)

let arr = [1,2,3];

[Link](1,0,"X");

[Link](arr);

✅ Output

[1,"X",2,3]
⚙️ Example (replace)

let arr = [1,2,3];

[Link](1,1,"X");

[Link](arr);

✅ Output

[1,"X",3]

⚡ Key Points

splice(start, deleteCount, newItems)


changes original array

🔥 FINAL DIFFERENCE

slice → copy part (no change)


splice → modify original

⚡ Interview One-Liner

“slice returns a shallow copy without modifying the original, while splice modifies the
original array by adding or removing elements.”

🔥 Common Built-in Object Methods

⚙️ 1. [Link]()

const obj = { a:1, b:2 };

[Link]([Link](obj));

✅ Output:

["a","b"]
⚙️ 2. [Link]()

[Link]([Link]({ a:1, b:2 }));

✅ Output:

[1,2]

⚙️ 3. [Link]()

[Link]([Link]({ a:1 }));

✅ Output:

[["a",1]]

⚙️ 4. hasOwnProperty()

const obj = { a:1 };

[Link]([Link]("a"));

✅ Output:

true

⚙️ 5. [Link]()

const a = { x:1 };
const b = { y:2 };

const c = [Link]({}, a, b);

[Link](c);

✅ Output:

{x:1, y:2}

⚡ Important Insight

Object methods = behavior of object


⚠️ Common Trap (this)

const obj = {
name: "JS",
greet: () => {
[Link]([Link]);
}
};

[Link]();

👉 Output: undefined

👉 Why:

 Arrow function has no own this

⚡ Interview One-Liner

“Object methods are functions defined inside objects that operate on object properties
using this.”

🔥 4. What is Destructuring?

🧠 Core Idea

Destructuring = extract values from arrays/objects into variables

👉 Cleaner way to access data

⚙️ 1. Array Destructuring

let arr = [10, 20, 30];

let [a, b, c] = arr;

[Link](a, b, c);

✅ Output

10 20 30
⚡ Skip values

let arr = [10, 20, 30];

let [a, , c] = arr;

[Link](a, c);

✅ Output:

10 30

⚙️ 2. Object Destructuring

let obj = {
name: "JS",
age: 10
};

let { name, age } = obj;

[Link](name, age);

✅ Output

JS 10

⚡ Rename variables

let { name: n } = obj;

[Link](n);

✅ Output:

JS

⚡ Default values
let { city = "India" } = obj;

[Link](city);

✅ Output:

India

⚙️ 3. Nested Destructuring

let obj = {
user: {
name: "JS"
}
};

let { user: { name } } = obj;

[Link](name);

✅ Output

JS

⚡ Why important?

 Cleaner code

 Less repetition

 Used in APIs & React

⚡ 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 (...)

👉 Same symbol (...) but different purpose based on usage

⚙️ 1. Spread Operator

🧠 Core Idea

Spread = expand / unpack values

⚙️ Example (Array)

let arr = [1,2,3];

let newArr = [...arr, 4];

[Link](newArr);

✅ Output

[1,2,3,4]

⚙️ Example (Object)

let obj = { a:1, b:2 };

let newObj = { ...obj, c:3 };

[Link](newObj);

✅ Output

{a:1, b:2, c:3}

🧠 Why?

 Copies values

 Used for cloning / merging

⚙️ 2. Rest Operator
🧠 Core Idea

Rest = collect multiple values into one

⚙️ Example (Function)

function sum(...nums) {
return nums;
}

[Link](sum(1,2,3));

✅ Output

[1,2,3]

⚙️ Example (Destructuring)

let [a, ...rest] = [1,2,3,4];

[Link](a);
[Link](rest);

✅ Output

1
[2,3,4]

🔥 KEY DIFFERENCE

Spread → expand values


Rest → collect values

⚡ Position Trick

Spread → right side


Rest → left side

⚠️ Common Confusion
let arr = [1,2,3];

[Link](...arr);

👉 Output:

123

👉 Spread breaks array into values

⚡ Interview One-Liner

“Spread expands elements, while rest collects multiple elements into a single variable,
though both use the same ... syntax.”

🔥 6. Shallow Copy vs Deep Copy

🧠 Core Idea

👉 Shallow Copy

Copies only first level


Nested objects still share reference

👉 Deep Copy

Copies everything (full structure)


No shared references

⚙️ 1. Shallow Copy

let obj1 = {
name: "JS",
address: { city: "BLR" }
};

let obj2 = { ...obj1 };

[Link] = "HYD";

[Link]([Link]); // ?
✅ Output

HYD

🧠 Why?

 Spread copies only top level

 address is still same reference

[Link] ─┐
├── same memory
[Link] ─┘

⚙️ 2. Deep Copy

let obj1 = {
name: "JS",
address: { city: "BLR" }
};

let obj2 = [Link]([Link](obj1));

[Link] = "HYD";

[Link]([Link]); // ?

✅ Output

BLR

🧠 Why?

 Entire object copied

 No shared memory

⚠️ Important Limitation

[Link]([Link](obj))

❌ Does NOT work for:


 functions

 undefined

 Date

⚙️ Better Deep Copy (modern)

let obj2 = structuredClone(obj1);

🔥 Key Difference

Shallow → copies top level only


Deep → copies full structure

⚡ 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.”

🔥 7. Array Methods (map, filter, reduce, find, forEach)

⚙️ 1. map()

🧠 Core Idea

👉 Transforms each element → returns new array

Example

let arr = [1,2,3];

let res = [Link](x => x * 2);

[Link](res);

✅ Output

[2,4,6]
⚙️ 2. filter()

🧠 Core Idea

👉 Returns elements that satisfy condition

Example

let arr = [1,2,3,4];

let res = [Link](x => x % 2 === 0);

[Link](res);

✅ Output

[2,4]

⚙️ 3. reduce()

🧠 Core Idea

👉 Reduces array to single value

Example

let arr = [1,2,3,4];

let sum = [Link]((acc, curr) => acc + curr, 0);

[Link](sum);

✅ Output

10

⚙️ 4. find()

🧠 Core Idea

👉 Returns first matching element


Example

let arr = [1,2,3,4];

let res = [Link](x => x > 2);

[Link](res);

✅ Output

⚙️ 5. forEach()

🧠 Core Idea

👉 Iterates array (no return)

Example

let arr = [1,2,3];

[Link](x => [Link](x));

✅ Output

1
2
3

🔥 Quick Comparison

map → transform → new array


filter → condition → new array
reduce → combine → single value
find → first match
forEach → just loop (no return)

⚡ 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.”

🔥 8. Difference between map() and forEach()

🧠 Core Idea

👉 Both iterate over arrays


👉 BUT behave very differently

⚙️ Example

let arr = [1,2,3];

let a = [Link](x => x * 2);


let b = [Link](x => x * 2);

[Link](a);
[Link](b);

✅ Output

[2,4,6]
undefined

🧠 Why?

🔹 map()

 Returns new array


 Stores transformed values

👉 [2,4,6]

🔹 forEach()

 Does not return anything

 Just runs function

👉 returns undefined

⚙️ Another Example

let arr = [1,2,3];

[Link](x => {
[Link](x * 2);
});

✅ Output

2
4
6

👉 Only prints, no array created

🔥 Key Differences

map → returns new array


forEach → returns undefined

map → used for transformation


forEach → used for side effects (logging, updating)

map → chainable
forEach → not chainable
⚠️ Interview Trap

let res = [Link](x => x * 2);


[Link](res);

👉 Output: undefined ❌

⚡ When to use what?

 Use map → when you need result array

 Use forEach → when you just want to loop

⚡ Interview One-Liner

“map returns a new transformed array, while forEach simply iterates over elements without
returning anything.”

🔥 1. What is this in JavaScript?

🧠 Core Idea

this = reference to the object that is calling the function

👉 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.”

🔥 2. this in Different Contexts

⚙️ 1. Global Context

[Link](this);

🧠 Output

 Browser → window

 Strict mode → undefined

⚙️ 2. Inside Normal Function

function test() {
[Link](this);
}

test();

🧠 Output

 Browser → window

 Strict mode → undefined

⚙️ 3. Inside Object Method

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?

 Arrow function has no own this

 Takes this from outer scope

⚡ Summary

Global → window / undefined


Function → window / undefined
Object → object itself
Arrow → inherits from outer scope

🔥 3. bind vs call vs apply


🧠 Core Idea

All are used to manually set this

⚙️ 1. call()

👉 Calls function immediately


👉 Arguments passed normally

function greet(age) {
[Link]([Link], age);
}

const obj = { name: "JS" };

[Link](obj, 25);

✅ Output

JS 25

⚙️ 2. apply()

👉 Same as call
👉 Arguments passed as array

[Link](obj, [25]);

✅ Output

JS 25

⚙️ 3. bind()

👉 Does NOT call immediately


👉 Returns new function

const fn = [Link](obj, 25);


fn();

✅ Output

JS 25
🔥 Key Differences

call → immediate call, args normal


apply → immediate call, args array
bind → returns new function

⚡ 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

call → call now


apply → apply array
bind → bind later

⚡ Pro Insight (this impresses)

👉 Most bugs happen because:

 this depends on how function is called, not defined

🔥 1. What is Prototype in JavaScript?

🧠 Core Idea

Prototype = an object from which other objects inherit properties and methods

👉 Every JS object has a hidden link to another object → called prototype

⚙️ Example

function Person(name) {
[Link] = name;
}
[Link] = function() {
[Link]("Hello " + [Link]);
};

const p = new Person("JS");


[Link]();

✅ Output

Hello JS

🧠 Why?

 greet is not inside object

 It is inside prototype

 Object accesses via prototype chain

⚡ Key Idea

Object → prototype → prototype → null

⚡ Interview One-Liner

“Prototype is an object that enables inheritance in JavaScript by allowing objects to share


properties and methods.”

🔥 2. __proto__ vs prototype

🧠 Difference

prototype → belongs to constructor function


__proto__ → belongs to object instance

⚙️ Example

function A() {}
const obj = new A();

[Link](obj.__proto__ === [Link]);

✅ Output

true

🧠 Meaning

 obj.__proto__ → points to [Link]

⚡ Simple View

[Link] → used to create objects


obj.__proto__ → link to that prototype

⚡ Interview One-Liner

“prototype is a property of constructor functions, while __proto__ is the internal link of


objects pointing to their prototype.”

🔥 3. Prototypal Inheritance

🧠 Core Idea

Objects inherit from other objects via prototype

⚙️ Example

const parent = {
greet() {
[Link]("Hello");
}
};

const child = [Link](parent);


[Link]();

✅ Output

Hello

🧠 Why?

 child has no greet

 JS looks in prototype → finds in parent

⚡ Prototype Chain

child → parent → Object → null

⚡ Interview One-Liner

“Prototypal inheritance allows objects to inherit properties from other objects through the
prototype chain.”

🔥 4. Constructor Functions

🧠 Core Idea

Constructor = function used to create multiple objects

⚙️ Example

function Person(name) {
[Link] = name;
}

const p1 = new Person("A");


const p2 = new Person("B");

[Link]([Link], [Link]);
✅ Output

AB

🧠 What new does

1. creates empty object


2. sets this → object
3. links prototype
4. returns object

⚡ Interview One-Liner

“Constructor functions are used to create multiple object instances using the new keyword.”

🔥 5. Classes in JavaScript

🧠 Core Idea

Class = clean syntax over prototype

⚙️ Example

class Person {
constructor(name) {
[Link] = name;
}

greet() {
[Link]("Hi " + [Link]);
}
}

const p = new Person("JS");


[Link]();

✅ Output

Hi JS
🧠 Important Truth

Class = syntactic sugar over prototype

⚙️ Inheritance

class A {
greet() {
[Link]("Hello");
}
}

class B extends A {}

const obj = new B();


[Link]();

✅ 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

Prototype → base object


__proto__ → object link
Inheritance → via prototype chain
Constructor → create objects
Class → modern syntax

🔥 1. What is DOM?

🧠 Core Idea
DOM (Document Object Model) =
representation of HTML as a tree of objects

👉 Browser converts HTML → JS object structure

⚙️ 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";

⚙️ 4. Add / Remove Elements

let div = [Link]("div");


[Link] = "New";

[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

When event happens → it travels through DOM

⚙️ Example Structure

<div>
<button>Click</button>
</div>

⚙️ Bubbling (default)

👉 Event goes:

button → div → body

⚙️ Example

[Link]("click", () => [Link]("button"));


[Link]("click", () => [Link]("div"));

✅ Output (click button)

button
div

⚙️ Capturing

👉 Event goes:

body → div → button

⚙️ Enable capturing

[Link]("click", () => [Link]("div"), true);


⚡ Difference

Bubbling → bottom → top


Capturing → top → bottom

⚡ Interview One-Liner

“Event bubbling propagates events from child to parent, while capturing propagates from
parent to child.”

🔥 4. Event Delegation

🧠 Core Idea

👉 Attach event to parent instead of multiple children

⚙️ Example

[Link]("list").addEventListener("click", (e) => {


[Link]([Link]);
});

🧠 Why?

 Works due to event bubbling

 Handles dynamic elements

 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

DOM → tree of HTML


Manipulation → change elements
Bubbling → child → parent
Capturing → parent → child
Delegation → parent handles children

🔥 Storage & Browser APIs

(localStorage vs sessionStorage vs cookies)

🧠 Core Idea

All are used to store data in browser, but differ in:

 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

👉 Stores data only for current tab/session

Example

[Link]("user", "A");

⚡ Features

Expires when tab closes


~5MB storage
Not shared across tabs

⚙️ 3. Cookies

🧠 Concept

👉 Small data stored and sent to server with every request


Example

[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

Feature localStorage sessionStorage cookies

Expiry No Tab close Yes

Size ~5MB ~5MB ~4KB

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.”

⚡ Real Usage Insight

localStorage → user settings


sessionStorage→ temporary data
cookies → authentication / tracking
🔥 ⚡ Arrays & Iteration

✅ 1. for...in vs for...of

🧠 Core Difference

for...in → keys (index / property names)


for...of → values

⚙️ Example

let arr = ["a", "b", "c"];

for (let i in arr) {


[Link](i);
}

✅ Output

0
1
2

for (let val of arr) {


[Link](val);
}

✅ Output

a
b
c

⚠️ Important

for (let key in obj) // for objects


for (let val of arr) // for arrays

⚡ Interview Line
“for...in iterates over keys, while for...of iterates over values of iterable objects.”

✅ 2. Iterators & Iterable Protocol

🧠 Core Idea

 Iterable → object you can loop (for...of)

 Iterator → object with next() method

⚙️ Example

let arr = [1,2,3];

let iterator = arr[[Link]]();

[Link]([Link]());
[Link]([Link]());

✅ Output

{ value: 1, done: false }


{ value: 2, done: false }

🧠 Meaning

Iterator → controls iteration


Iterable → provides iterator

🔥 ⚡ Functions (Advanced)

✅ 3. Pure Functions

🧠 Core Idea

👉 Same input → same output


👉 No side effects
function add(a, b) {
return a + b;
}

✔ predictable ✔ safe

❌ 4. Impure Functions

🧠 Core Idea

👉 Depends on external data OR modifies state

let x = 10;

function add(a) {
return a + x;
}

❌ depends on outside variable

⚡ Difference

Pure → predictable
Impure → unpredictable

✅ 5. Function Composition

🧠 Core Idea

👉 Combine multiple functions

const add = x => x + 2;


const multiply = x => x * 3;

const result = multiply(add(2));

[Link](result);

✅ Output

12
👉 Output flows:

add → multiply

✅ 6. Generator Function (function*)

🧠 Core Idea

👉 Function that can pause and resume

⚙️ Example

function* gen() {
yield 1;
yield 2;
}

const g = gen();

[Link]([Link]());
[Link]([Link]());

✅ Output

{ value: 1, done: false }


{ value: 2, done: false }

🧠 Why?

 yield pauses execution

 next() resumes

🔥 ⚡ Execution & Engine (Deep)

✅ 7. Lexical Environment
🧠 Core Idea

👉 Structure that stores variables + scope info

let a = 10;

function test() {
[Link](a);
}

👉 test remembers where it was created

⚡ Interview Line

“Lexical environment stores variables and scope chain for execution.”

✅ 8. Variable Environment

🧠 Core Idea

👉 Part of execution context


👉 Stores var variables

var a = 10;

👉 stored in variable environment

⚡ Key Difference

Lexical → let, const


Variable → var

✅ 9. Stack vs Heap Memory


🧠 Stack

 Stores primitive values

 Fast

 Fixed size

let a = 10;

🧠 Heap

 Stores objects

 Dynamic size

let obj = { name: "JS" };

⚡ Difference

Stack → simple values


Heap → objects & references

✅ 10. Garbage Collection (Mark & Sweep)

🧠 Core Idea

👉 Removes unused memory automatically

⚙️ Example

let obj = { name: "JS" };

obj = null;

👉 Old object → no reference → deleted

🧠 How it works (Mark & Sweep)

1. Mark reachable objects


2. Remove unreachable ones
⚡ Interview Line

“Garbage collection uses mark-and-sweep to remove unreachable objects from memory.”

You might also like