JS Complete Notes
JS Complete Notes
Contents
SECTION 1: Introduction & Setup.........................................................................................................1
1.1 What is JavaScript?....................................................................................................................1
1.2 Goals of this Series.....................................................................................................................1
1.3 Environment Setup.....................................................................................................................1
▶ [Link] Installation....................................................................................................................1
▶ VS Code Editor Setup...............................................................................................................1
▶ GitHub Codespaces..................................................................................................................1
SECTION 2: Variables & Data Types....................................................................................................1
2.1 Variables — Declaration Keywords............................................................................................1
2.2 Memory: Stack vs Heap..............................................................................................................1
2.3 Primitive Data Types...................................................................................................................1
2.4 Non-Primitive (Reference) Types................................................................................................1
SECTION 3: Type Conversion & Operations........................................................................................1
3.1 Explicit Type Conversion............................................................................................................1
3.2 Implicit Type Coercion................................................................................................................1
3.3 NaN (Not a Number)...................................................................................................................1
3.4 Prefix vs Postfix Operators.........................................................................................................1
SECTION 4: Control Flow & Logic........................................................................................................1
4.1 If-Else Statements.......................................................................................................................1
4.2 Switch-Case................................................................................................................................1
4.3 Truthy & Falsy Values.................................................................................................................1
4.4 Nullish Coalescing Operator (??)................................................................................................1
4.5 Ternary Operator........................................................................................................................1
SECTION 5: Loops & Iteration..............................................................................................................1
5.1 For Loop......................................................................................................................................1
5.2 While & Do-While Loops.............................................................................................................1
5.3 for...of — Iterating Values...........................................................................................................1
5.4 for...in — Iterating Object Keys...................................................................................................1
5.5 forEach, map, filter, reduce.........................................................................................................1
SECTION 6: Functions..........................................................................................................................1
6.1 Function Declaration vs Expression............................................................................................1
6.2 Arrow Functions..........................................................................................................................1
6.3 Parameters, Arguments & Rest Operator...................................................................................1
6.4 IIFE — Immediately Invoked Function Expression.....................................................................1
SECTION 7: Objects In Depth...............................................................................................................1
7.1 Object Literals vs Singleton........................................................................................................1
7.2 Destructuring...............................................................................................................................1
7.3 Spread & Rest Operators............................................................................................................1
7.4 JSON API Basics........................................................................................................................1
SECTION 8: Execution Context & Call Stack........................................................................................1
8.1 What is Execution Context?........................................................................................................1
8.2 The Call Stack.............................................................................................................................1
SECTION 9: DOM Manipulation............................................................................................................1
9.1 What is the DOM?.......................................................................................................................1
9.2 Selecting Elements.....................................................................................................................1
9.3 Modifying Elements.....................................................................................................................1
9.4 Creating & Removing Elements..................................................................................................1
SECTION 10: Event Handling...............................................................................................................1
10.1 Adding Event Listeners.............................................................................................................1
10.2 Event Object.............................................................................................................................1
10.3 Event Bubbling & Capturing......................................................................................................1
10.4 Event Delegation.......................................................................................................................1
SECTION 11: Closures & Lexical Scope...............................................................................................1
11.1 Lexical Scoping.........................................................................................................................1
11.2 What is a Closure?....................................................................................................................1
11.3 Practical Closure Patterns........................................................................................................1
SECTION 12: Prototypes & Classes.....................................................................................................1
12.1 Prototypal Inheritance...............................................................................................................1
12.2 ES6 Classes.............................................................................................................................1
12.3 Inheritance with extends...........................................................................................................1
12.4 Getters & Setters......................................................................................................................1
SECTION 13: Asynchronous JavaScript...............................................................................................1
13.1 The JavaScript Event Loop.......................................................................................................1
13.2 Promises...................................................................................................................................1
13.3 Promise Combinators...............................................................................................................1
13.4 Fetch API & Async/Await..........................................................................................................1
SECTION 14: Practical Mini Projects....................................................................................................1
Project 1 — Color Switcher................................................................................................................1
Project 2 — BMI Calculator................................................................................................................1
Project 3 — Number Guessing Game...............................................................................................1
Project 4 — Digital Clock...................................................................................................................1
SECTION 15: Dates, Strings & Math.....................................................................................................1
15.1 Date Object...............................................................................................................................1
15.2 String Methods..........................................................................................................................1
15.3 Math Object...............................................................................................................................1
SECTION 16: Interview Q&A & Quick Reference.................................................................................1
16.1 Top 25 JavaScript Interview Questions....................................................................................1
▶ Q1: What is the difference between var, let, and const?..........................................................1
▶ Q2: What is hoisting?................................................................................................................1
▶ Q3: Explain closures with an example......................................................................................1
▶ Q4: What is the difference between == and ===?....................................................................1
▶ Q5: What is the event loop?......................................................................................................1
▶ Q6: What are Promises and how do they differ from callbacks?..............................................1
▶ Q7: What is event bubbling and how do you stop it?................................................................1
▶ Q8: What is event delegation?..................................................................................................1
▶ Q9: What is the difference between null and undefined?.........................................................1
▶ Q10: How does prototypal inheritance work?...........................................................................1
▶ Q11: What is 'this' in JavaScript?..............................................................................................1
▶ Q12: What is the difference between shallow copy and deep copy?.......................................1
▶ Q13: What is an IIFE?...............................................................................................................1
▶ Q14: What are truthy and falsy values?....................................................................................1
▶ Q15: Explain map(), filter(), and reduce().................................................................................1
16.2 Cheat Sheet — Key Syntax......................................................................................................1
16.3 Common Mistakes to Avoid......................................................................................................1
SECTION 17: Advanced Topics & Next Steps......................................................................................1
17.1 ES6+ Features Summary.........................................................................................................1
17.2 What to Learn Next...................................................................................................................1
17.3 Recommended Learning Path..................................................................................................1
📚 10+ Topics 💻 Code Examples 🚀 Real Projects
Single-threaded One call stack, one thing at a Event loop handles async
time
🌍 REAL-WORLD USE: Every website you use — Google, Amazon, Instagram — uses JavaScript
for its interactivity: dropdown menus, form validation, infinite scroll, animations, and live updates.
💡 SMART TIP: Watch each video at least twice — once to understand the concept, once to code
along. This dual approach doubles retention.
Current (Latest) Latest features, experimental ⚠️Use only for learning latest
syntax
💡 SMART TIP: Enable 'Format on Save' in VS Code settings (Editor: Format On Save → true).
This ensures your code is always neatly formatted without manual effort.
▶ GitHub Codespaces
GitHub Codespaces provides a full VS Code development environment in the browser. Useful
when you cannot install software on a machine — ideal for learning in school labs or on tablets.
• No local installation required
• Full Linux environment with [Link] pre-installed
• Sync with your GitHub repositories automatically
🌍 REAL-WORLD USE: Many companies use cloud-based IDEs like Codespaces or GitPod so
developers can start coding immediately on any device without lengthy setup.
SECTION 2: Variables & Data Types
📄 [Link]
// var — function-scoped, causes issues (AVOID)
var name = 'Ariyan';
var name = 'Bob'; // Re-declaration allowed — confusing!
⚠️ WARNING: Never use var in modern JavaScript. It is function-scoped, hoisted weirdly, and can
be redeclared — causing subtle bugs that are hard to debug.
💡 SMART TIP: Use const by default. Switch to let only when you know the variable's value will
change. This habit prevents 90% of accidental mutation bugs.
📄 [Link]
// STACK — copy by value
let a = 10;
let b = a; // b gets a COPY of 10
b = 20;
[Link](a); // 10 — a unchanged
🌍 REAL-WORLD USE: In React apps, directly mutating state objects causes bugs because React
compares references. You must always create new objects (spread operator or [Link]) to
trigger proper re-renders.
Number 42, 3.14, -7, NaN, Infinity All numbers are 64-bit floats
📄 [Link]
// String — multiple ways to create
let s1 = 'single quotes';
let s2 = "double quotes";
let s3 = `template literal: ${s1}`; // Backtick — can embed expressions
// Number quirks
[Link](0.1 + 0.2); // 0.30000000000000004 ← floating point issue!
[Link]([Link](NaN)); // true
[Link](typeof NaN); // 'number' ← weird but true
// null vs undefined
let empty = null; // You explicitly set this to empty
let notSet; // JavaScript sets this to undefined
[Link](typeof null); // 'object' ← famous JS bug (never fixed)
💡 SMART TIP: Use typeof to check variable types. But remember: typeof null === 'object' is a 30-
year-old bug in JS that will never be fixed for backwards compatibility.
📄 [Link]
// Array
let fruits = ['apple', 'banana', 'mango'];
[Link](fruits[0]); // 'apple'
[Link]([Link]); // 3
// Object
let person = {
name: 'Ariyan',
age: 20,
isStudent: true,
address: { city: 'Kolkata', pin: 700001 } // nested object
};
[Link]([Link]); // 'Ariyan' — dot notation
[Link](person['age']); // 20 — bracket notation
[Link]([Link]); // 'Kolkata' — chaining
🌍 REAL-WORLD USE: Every API response you receive from a server is a JavaScript object
(JSON). Mastering object access patterns is essential for working with real backend data.
SECTION 3: Type Conversion & Operations
📄 [Link]
// String to Number
Number('42') // 42
Number('42.5') // 42.5
Number('hello') // NaN (Not a Number)
Number('') // 0
Number(true) // 1
Number(false) // 0
Number(null) // 0
Number(undefined) // NaN
// Number to String
String(42) // '42'
(42).toString() // '42'
(42).toString(2) // '101010' ← binary!
(255).toString(16) // 'ff' ← hexadecimal!
// To Boolean
Boolean(0) // false
Boolean('') // false
Boolean(null) // false
Boolean(undefined) // false
Boolean(NaN) // false
Boolean('hello') // true
Boolean(42) // true
Boolean([]) // true ← empty array is truthy!
Boolean({}) // true ← empty object is truthy!
⚠️ WARNING: Number('') returns 0, not NaN! This surprises many developers. Always validate user
inputs with isNaN() before using Number() on form data.
💡 SMART TIP: Use parseInt() when parsing user inputs or CSS values like '42px'. Number() fails
on these but parseInt() handles them gracefully.
📄 [Link]
// String + Number = String concatenation
'5' + 3 // '53' ← NOT 8!
'5' - 3 // 2 ← subtraction converts string to number
'5' * '3' // 15 ← multiplication forces numeric conversion
⚠️ WARNING: ALWAYS use === (strict equality) instead of == in production code. Loose equality
has 50+ edge cases that trip up even experienced developers.
📄 [Link]
let x = 5;
[Link](++x); // 6 — incremented before printing
[Link](x++); // 6 — printed before incrementing
[Link](x); // 7 — x is now 7
SECTION 4: Control Flow & Logic
4.2 Switch-Case
Switch is ideal when comparing one variable against multiple possible values. More readable than
long if-else chains.
📄 [Link]
let day = 'Monday';
switch (day) {
case 'Monday':
case 'Tuesday':
[Link]('Weekday — work time!');
break;
case 'Saturday':
case 'Sunday':
[Link]('Weekend — rest!');
break;
default:
[Link]('Mid-week');
}
⚠️ WARNING: Always include break at the end of each case. Without break, execution 'falls
through' to the next case — a common bug.
4.3 Truthy & Falsy Values
In JavaScript, every value has an inherent boolean nature. Understanding this is critical for writing
clean conditions.
false true
📄 [Link]
// Practical truthy/falsy usage
let username = '';
if (username) {
[Link]('Hello, ' + username);
} else {
[Link]('Please enter a username'); // ← runs (empty string is falsy)
}
🌍 REAL-WORLD USE: When building dashboards with API data, use ?? to set fallback values for
missing data points without accidentally replacing valid zeros or empty strings.
// Ternary equivalent
let status2 = age >= 18 ? 'Adult' : 'Minor';
💡 SMART TIP: Use ternary for simple yes/no conditions. For 3+ conditions, stick with if-else or
switch for readability.
SECTION 5: Loops & Iteration
// Reverse loop
for (let i = [Link] - 1; i >= 0; i--) {
[Link](fruits[i]); // mango, banana, apple
}
🌍 REAL-WORLD USE: Do-while is perfect for user input validation in CLI apps — ask at least
once, then keep asking until valid input is received.
5.3 for...of — Iterating Values
for...of iterates over the VALUES of any iterable (arrays, strings, Sets, Maps, etc.). Clean and
readable.
📄 [Link]
// Array values
let colors = ['red', 'green', 'blue'];
for (let color of colors) {
[Link](color); // red, green, blue
}
// String characters
for (let char of 'hello') {
[Link](char); // h, e, l, l, o
}
// Map iteration
let map = new Map([['name', 'Ariyan'], ['age', 20]]);
for (let [key, val] of map) {
[Link](key, '->', val);
}
⚠️ WARNING: Never use for...in to loop over arrays. It iterates over ALL enumerable properties
(including any added to [Link]) and gives string indices, not numbers.
🌍 REAL-WORLD USE: In React, map() is used to render lists of components. filter() is used for
search/filter features. reduce() is used for cart totals, statistics, and grouping data.
💡 SMART TIP: Method chaining (filter().map().reduce()) is a powerful pattern. Break complex data
transformations into readable chains instead of nested loops.
SECTION 6: Functions
Hoisted — can call before definition NOT hoisted — must define before calling
📄 [Link]
// Declaration — hoisted
[Link](add(2, 3)); // Works! (hoisted)
function add(a, b) {
return a + b;
}
// No parameters
const greet = () => 'Hello!';
// Multiple parameters
const add = (a, b) => a + b;
⚠️ WARNING: Arrow functions should NOT be used as object methods because they don't have
their own 'this'. Use regular functions for methods that need to access the object via 'this'.
📄 [Link]
// Object literal (recommended)
const user = {
name: 'Ariyan',
age: 20,
'full name': 'Ariyan Das', // key with space — use quotes
greet() { // method shorthand (ES6)
return `Hello, I'm ${[Link]}`;
}
};
// Property access
[Link]; // 'Ariyan' — dot notation
user['full name']; // 'Ariyan Das' — bracket (needed for keys with spaces)
// Object methods
[Link](user); // ['name', 'age', 'full name', 'greet']
[Link](user); // ['Ariyan', 20, 'Ariyan Das', function]
[Link](user); // [['name','Ariyan'], ['age',20], ...]
7.2 Destructuring
Destructuring lets you extract values from objects and arrays into variables in one concise
statement.
📄 [Link]
// Object destructuring
const person = { name: 'Ariyan', age: 20, city: 'Kolkata' };
// Traditional way
const name1 = [Link];
const age1 = [Link];
// Destructuring way
const { name, age, city } = person;
// Rename while destructuring
const { name: fullName, age: years } = person;
[Link](fullName); // 'Ariyan'
// Default values
const { name, country = 'India' } = person;
[Link](country); // 'India' (not in object, uses default)
// Nested destructuring
const course = { title: 'JS', teacher: { name: 'Hitesh', city: 'Delhi' } };
const { teacher: { name: teacherName } } = course;
// Array destructuring
const [first, second, ...rest] = [10, 20, 30, 40, 50];
// first = 10, second = 20, rest = [30, 40, 50]
// Copy an array
const original = [1, 2, 3];
const copy = [...original];
// Merge arrays
const merged = [...original, ...copy, 4, 5];
// Override properties
const updated = { ...obj1, b: 99 }; // { a: 1, b: 99 }
🌍 REAL-WORLD USE: Every REST API sends and receives JSON. When you fetch data from a
backend, it arrives as a JSON string. [Link]() converts it to a usable JS object.
SECTION 8: Execution Context & Call Stack
Memory (Creation) Phase Allocates memory for all var x = undefined; function foo
variables and functions {...}
Execution Phase Runs code line by line, assigns x = 10; foo() called
values
📄 [Link]
// Global Execution Context created first
let x = 10; // Memory phase: x = undefined → Exec: x = 10
📄 [Link]
// Call stack visualization
function multiply(a, b) {
return a * b; // Stack: [global, add, multiply]
}
function add(a, b) {
return multiply(a, b) + 1; // Stack: [global, add]
}
📌 NOTE: Open Chrome DevTools → Sources → add a breakpoint. The 'Call Stack' panel on the
right shows the exact stack at that moment. This is how you debug complex applications.
🌍 REAL-WORLD USE: Understanding the call stack is crucial for debugging. Every stack trace in
an error message IS the call stack at the moment the error occurred — reading it bottom-up shows
you the chain of function calls.
SECTION 9: DOM Manipulation
📄 [Link]
<!-- Example HTML structure -->
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1 id='title'>Hello</h1>
<ul class='list'>
<li>Item 1</li>
<li>Item 2</li>
</ul>
</body>
</html>
/* DOM Tree:
* document
* └── html
* ├── head → title
* └── body → h1, ul → li, li
*/
📄 [Link]
// getElementById
const title = [Link]('title');
[Link]([Link]); // 'Hello'
// Change styling
[Link] = 'red';
[Link] = '2rem';
[Link] = '#333';
// Change attributes
const img = [Link]('img');
[Link]('src', '[Link]');
[Link]('alt', 'New photo');
// Class manipulation
[Link]('highlight');
[Link]('old-class');
[Link]('active'); // adds if not present, removes if present
[Link]('active'); // true/false
// REMOVE element
const oldEl = [Link]('.old');
[Link](); // modern way
[Link](oldEl); // older way
🌍 REAL-WORLD USE: E-commerce websites dynamically create product cards using
createElement and inject them into the grid — no page reload needed. This is the foundation of
Single Page Applications.
SECTION 10: Event Handling
[Link]('click', function(event) {
[Link]('Button clicked!');
[Link]([Link]); // the element that was clicked
});
// Form event
const form = [Link]('form');
[Link]('submit', (e) => {
[Link](); // ← STOP default form submission (page reload)
const input = [Link]('#name').value;
[Link]('Form submitted with:', input);
});
Default behavior (3rd arg: false) Use 3rd arg: true to enable
📄 [Link]
<div id='outer'>
<div id='inner'>
<button id='btn'>Click me</button>
</div>
</div>
// Stop bubbling
[Link]('#btn').addEventListener('click', (e) => {
[Link](); // Only 'Button' logs, inner and outer won't fire
[Link]('Button');
});
// With delegation — GOOD (one listener for all li's, including future ones)
[Link]('ul').addEventListener('click', (e) => {
if ([Link] === 'LI') {
[Link]('Clicked:', [Link]);
[Link]('done');
}
});
🌍 REAL-WORLD USE: To-do list apps, accordion menus, and infinite scroll feeds all use event
delegation because list items are constantly added/removed.
💡 SMART TIP: Event delegation is a top interview question. Explain why it improves performance
(fewer event listeners in memory) and handles dynamically added elements.
SECTION 11: Closures & Lexical Scope
function outer() {
let outerVar = 'I am outer';
function inner() {
let innerVar = 'I am inner';
// Can access: innerVar, outerVar, globalVar
[Link](globalVar); // ✅
[Link](outerVar); // ✅
[Link](innerVar); // ✅
}
inner();
// Cannot access: innerVar
// [Link](innerVar); // ❌ ReferenceError
}
return {
increment() { count++; },
decrement() { count--; },
getCount() { return count; }
};
}
🌍 REAL-WORLD USE: React's useState hook is built on closures — each component instance
has its own private state that persists between renders.
💡 SMART TIP: Closure is THE most asked JavaScript interview question. Practice explaining it in
one sentence: A closure is when an inner function retains access to its outer function's variables even
after the outer function has returned.
SECTION 12: Prototypes & Classes
constructor(name, email) {
[Link] = name;
[Link] = email;
[Link]++;
}
// Instance method
greet() {
return `Hello, I'm ${[Link]}`;
}
info() {
return `${[Link]()} — Breed: ${[Link]}`; // call parent method
}
}
🌍 REAL-WORLD USE: Getters and setters are used in frameworks like [Link] to implement
reactive data — when a value is 'set', the UI automatically re-renders.
SECTION 13: Asynchronous JavaScript
Web APIs Handles async tasks outside JS setTimeout, fetch, DOM events
Event Loop Moves tasks from queues to Checks queues when stack
stack empty
📄 [Link]
[Link]('Start'); // 1st — synchronous
setTimeout(() => {
[Link]('Timeout'); // 3rd — goes to callback queue
}, 0);
[Link]().then(() => {
[Link]('Promise'); // 2nd — microtask queue (higher priority!)
});
[Link]('End'); // synchronous
📌 NOTE: Promises (microtask queue) always run BEFORE setTimeout callbacks (callback queue),
even with setTimeout(fn, 0). Microtasks have higher priority.
13.2 Promises
A Promise is an object representing the eventual completion or failure of an asynchronous
operation. It has three states: Pending → Fulfilled OR Rejected.
📄 [Link]
// Creating a Promise
const fetchData = new Promise((resolve, reject) => {
// Simulate async operation
setTimeout(() => {
const success = true;
if (success) {
resolve({ data: 'User data', status: 200 });
} else {
reject(new Error('Network error'));
}
}, 2000);
});
// Consuming a Promise
fetchData
.then(result => {
[Link]('Success:', [Link]);
return [Link]; // Chain: return value passes to next .then()
})
.then(data => {
[Link]('Processed:', [Link]());
})
.catch(error => {
[Link]('Error:', [Link]);
})
.finally(() => {
[Link]('Done — whether success or error');
// Good for: hide loading spinner, cleanup
});
if (![Link]) {
throw new Error(`HTTP ${[Link]}`);
}
} catch (error) {
[Link]('Error:', [Link]);
}
}
getUser('hiteshchoudhary');
🌍 REAL-WORLD USE: Every modern web app fetches data from APIs using fetch + async/await.
Weather apps, news feeds, e-commerce product listings, social media feeds — all powered by this
pattern.
💡 SMART TIP: Always wrap async/await in try-catch. Unhandled promise rejections crash your
application and are hard to debug without proper error handling.
SECTION 14: Practical Mini Projects
Applying theory through projects is the fastest way to solidify understanding. These four projects
from the series demonstrate core concepts in action.
[Link]('click', () => {
[Link] = '';
});
[Link]('#calcBtn').addEventListener('click', () => {
const weight = parseFloat([Link]('#weight').value);
const height = parseFloat([Link]('#height').value) / 100; // cm
to m
let category;
if (bmi < 18.5) category = 'Underweight';
else if (bmi < 24.9) category = 'Normal weight';
else if (bmi < 29.9) category = 'Overweight';
else category = 'Obese';
[Link]('#result').innerHTML =
`<strong>BMI: ${bmi}</strong><br>Category: ${category}`;
});
[Link]('#guessBtn').addEventListener('click', () => {
const guess = parseInt([Link]('#guessInput').value);
[Link](guess);
attemptsLeft--;
[Link]('#previous').textContent =
'Previous: ' + [Link](', ');
});
// Update DOM
[Link]('#time').textContent = `${hours}:${minutes}:${seconds}`;
[Link]('#date').textContent = dateStr;
}
🌍 REAL-WORLD USE: Timers with setInterval power dashboards, live score tickers, countdown
timers, and session timeout warnings in web applications.
SECTION 15: Dates, Strings & Math
// Get components
[Link](); // 2025
[Link](); // 0-11 (0 = January!)
[Link](); // 1-31 (day of month)
[Link](); // 0-6 (0 = Sunday!)
[Link](); // 0-23
[Link](); // 0-59
[Link](); // 0-59
[Link](); // milliseconds since epoch
// Formatting
[Link](); // '2025-01-15T10:30:00.000Z'
[Link](); // 'Wed Jan 15 2025'
[Link]('en-IN'); // '15/1/2025'
⚠️ WARNING: Months are 0-indexed (0=January, 11=December). This trips up almost every
developer at least once!
[Link](1, 5, 3); // 5
[Link](1, 5, 3); // 1
[Link](2, 8); // 256
[Link](144); // 12
▶ Q6: What are Promises and how do they differ from callbacks?
A Promise is an object representing eventual completion/failure of async operations. Unlike
callbacks, promises avoid 'callback hell' by supporting chaining (.then().catch()). They have three
states: pending, fulfilled, rejected. Async/await is built on promises and makes async code look
synchronous.
▶ Q7: What is event bubbling and how do you stop it?
Event bubbling is when an event on an element propagates up through its ancestors. For example,
clicking a button also 'fires' the click on its parent divs. Stop it with [Link]().
[Link]() is different — it stops the browser's default action (like form submit
navigation) but doesn't stop bubbling.
▶ Q12: What is the difference between shallow copy and deep copy?
Shallow copy copies only the top-level properties. Nested objects are still referenced. Methods:
spread {...obj}, [Link](). Deep copy creates completely independent copies at all levels.
Methods: [Link]([Link](obj)) (limitations: no functions/undefined), structuredClone()
(modern), or lodash cloneDeep.
📄 [Link]
// ── Variables ─────────────────────────────────────────
const PI = 3.14; // Block-scoped, no reassign
let count = 0; // Block-scoped, reassignable
// ── Destructuring ─────────────────────────────────────
const { name, age = 18 } = user;
const [first, ...rest] = array;
// ── Spread ────────────────────────────────────────────
const newArr = [...arr1, ...arr2];
const newObj = { ...obj1, extra: true };
// ── Async/Await ───────────────────────────────────────
async function fetchUser(id) {
try {
const res = await fetch(`/api/users/${id}`);
if (![Link]) throw new Error([Link]);
return await [Link]();
} catch (e) { [Link](e); }
}
// ── Class ─────────────────────────────────────────────
class Animal {
#name; // Private field (ES2022)
constructor(name) { this.#name = name; }
get name() { return this.#name; }
}
Mutating state directly Breaks React re-renders, Spread to create new objects
causes bugs
Not handling Promise rejections Unhandled rejection crashes Always use .catch() or try-catch
the app
typeof null === 'object' Trusting typeof for null checks Use === null explicitly
Arrow function as method No own 'this', wrong context Use regular function for
methods
Direct innerHTML with user XSS vulnerability Use textContent for user data
input
SECTION 17: Advanced Topics & Next Steps
Map & Set new Map(), new Set() Advanced data structures
Phase 2 DOM & Events mastery Todo app, Quiz app, Form
validator
🌍 REAL-WORLD USE: Hitesh Choudhary (Chai aur Code) teaches on the principle that
understanding internals makes you better than 90% of developers who just copy-paste. Keep asking
'Why does this work?' for every concept.
💡 SMART TIP: The best way to learn programming is by building projects that you actually want to
use. Build a clone of your favourite app — it forces you to encounter and solve real problems.