0% found this document useful (0 votes)
3 views50 pages

JS Complete Notes

JS_Complete_Notes

Uploaded by

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

JS Complete Notes

JS_Complete_Notes

Uploaded by

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

JavaScript

Complete Notes Book


From Basics to Advanced | 80+ Pages

Based on: JavaScript Series (Chai aur Code)


Video 1: JavaScript Fundamentals & Basics | Video 2: DOM, Async & Advanced JS

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

Compiled by: Ariyan | 4th Semester CST | 2025–26


SECTION 1: Introduction & Setup

1.1 What is JavaScript?


JavaScript (JS) is a lightweight, interpreted, high-level programming language primarily used to
make web pages interactive. It is one of the three core technologies of the World Wide Web
alongside HTML and CSS.
Originally created in 1995 by Brendan Eich in just 10 days, JS has grown into a versatile language
capable of running both in the browser (frontend) and on servers (backend via [Link]).

Feature Description Example

Interpreted Code runs line-by-line without Browser reads JS directly


pre-compilation

Dynamic Typing Variable types are determined let x = 5; x = 'hello';


at runtime

Prototype-based Inheritance via prototypes, not obj.__proto__


classic classes

Single-threaded One call stack, one thing at a Event loop handles async
time

Multi-paradigm Supports OOP, functional, Flexible coding styles


procedural

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

1.2 Goals of this Series


The Chai aur Code JavaScript series has three primary goals for every learner:
• Build Confidence: Move from 'I can't code' to 'I can build things' through project-based practice
• Project-Based Learning: Learn by building real mini-projects — not just reading theory
• Interview Preparation: Every concept is taught with interview questions in mind

💡 SMART TIP: Watch each video at least twice — once to understand the concept, once to code
along. This dual approach doubles retention.

1.3 Environment Setup


▶ [Link] Installation
[Link] is a JavaScript runtime that lets you run JS outside the browser. It is essential for backend
development, running scripts, and package management via npm.

Version Use Case Recommendation


LTS (Long-Term Support) Production apps, stable APIs ✅ Use this for projects

Current (Latest) Latest features, experimental ⚠️Use only for learning latest
syntax

Older versions Legacy codebases ❌ Avoid unless required

Terminal Commands — [Link] Setup


# Check if [Link] is installed
node --version // Outputs: v20.x.x

# Check npm version


npm --version // Outputs: 10.x.x

# Run a JavaScript file


node [Link]

▶ VS Code Editor Setup


Visual Studio Code (VS Code) is the most popular code editor for JavaScript development. Key
extensions to install:
• Prettier — Code formatter (formats code automatically on save)
• ESLint — Linter that catches errors before you run code
• Live Server — Runs a local dev server, auto-refreshes browser
• JavaScript (ES6) code snippets — Quick code templates
• GitLens — Enhanced Git integration inside VS Code

💡 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

2.1 Variables — Declaration Keywords


Variables are named containers for storing data values. JavaScript provides three declaration
keywords, each with different scoping rules and behaviors.

Keyword Scope Reassignable?

Var Function / Global scope Yes (avoid in modern JS)

Let Block scope { } Yes

const Block scope { } No (value fixed)

📄 [Link]
// var — function-scoped, causes issues (AVOID)
var name = 'Ariyan';
var name = 'Bob'; // Re-declaration allowed — confusing!

// let — block-scoped, reassignable


let age = 20;
age = 21; // OK — reassignment allowed

// const — block-scoped, fixed reference


const PI = 3.14159;
// PI = 3; // ❌ TypeError: Assignment to constant variable

// const with objects — reference is fixed, contents can change


const user = { name: 'Ariyan' };
[Link] = 'Bob'; // ✅ OK — modifying property
// user = {}; // ❌ Error — cannot reassign

⚠️ 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.

2.2 Memory: Stack vs Heap


Understanding where JavaScript stores values in memory is key to understanding why primitives
and objects behave differently.

Stack (Primitives) Heap (Reference Types)

Stores actual values Stores references (memory addresses)

Fixed size, fast access Dynamic size, slower access

Copied by value Copied by reference


string, number, boolean, null, undefined, symbol, Objects, Arrays, Functions
bigint

📄 [Link]
// STACK — copy by value
let a = 10;
let b = a; // b gets a COPY of 10
b = 20;
[Link](a); // 10 — a unchanged

// HEAP — copy by reference


let obj1 = { city: 'Kolkata' };
let obj2 = obj1; // obj2 points to SAME memory
[Link] = 'Delhi';
[Link]([Link]); // 'Delhi' — obj1 CHANGED!

// Fix: create a true copy


let obj3 = { ...obj1 }; // Spread operator = shallow copy
[Link] = 'Mumbai';
[Link]([Link]); // 'Delhi' — obj1 safe now

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

2.3 Primitive Data Types


Primitive types are the building blocks of JavaScript data. There are 7 primitive types:

Type Example Values Notes

String "Hello", 'World' UTF-16, immutable, text data

Number 42, 3.14, -7, NaN, Infinity All numbers are 64-bit floats

Boolean true, false Logical true/false

Null null Intentional absence of value


(typeof: 'object' — JS quirk!)

undefined undefined Uninitialized variable default

Symbol Symbol('id') Unique identifier, ES6+

BigInt 9007199254740991n Integers beyond


Number.MAX_SAFE_INTEGER

📄 [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)

// Symbol — always unique


let id1 = Symbol('id');
let id2 = Symbol('id');
[Link](id1 === id2); // false — always unique!

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

2.4 Non-Primitive (Reference) Types


Non-primitive types store collections of data or more complex entities. They are stored on the heap
and accessed by reference.
• Arrays — Ordered, indexed collections. Can hold mixed types.
• Objects — Key-value pairs. The most fundamental data structure in JS.
• Functions — First-class objects. Can be passed as arguments, returned, stored in variables.

📄 [Link]
// Array
let fruits = ['apple', 'banana', 'mango'];
[Link](fruits[0]); // 'apple'
[Link]([Link]); // 3

// Mixed-type array (valid in JS)


let mixed = [1, 'hello', true, null, { name: 'Ariyan' }];

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

3.1 Explicit Type Conversion


Type conversion (casting) is when you deliberately convert a value from one type to another using
built-in functions.

📄 [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!

// parseInt and parseFloat


parseInt('42px') // 42 (stops at non-numeric)
pa0rseFloat('3.14abc') // 3.14
parseInt('0xFF', 16) // 255 (hex to decimal)

⚠️ 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.

3.2 Implicit Type Coercion


Coercion happens automatically when JavaScript tries to match types for operations. This is a
major source of bugs for beginners.

📄 [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

// Loose equality (==) performs coercion


0 == false // true ← coercion!
'' == false // true ← coercion!
null == undefined // true ← special rule
null == 0 // false ← null only equals undefined

// Strict equality (===) — NO coercion


0 === false // false ← different types
'' === false // false
'5' === 5 // false
null === undefined // false

⚠️ WARNING: ALWAYS use === (strict equality) instead of == in production code. Loose equality
has 50+ edge cases that trip up even experienced developers.

3.3 NaN (Not a Number)


NaN is a special numeric value that represents an invalid or unrepresentable mathematical
operation. It has the unique property of not being equal to itself.
📄 [Link]
[Link](NaN === NaN); // false ← NaN is not equal to itself!
[Link]([Link](NaN)); // true ← correct way to check
[Link](isNaN('hello')); // true ← converts first, then checks
[Link]([Link]('hello'));// false ← stricter: only true for NaN itself

// Common ways NaN appears


0 / 0 // NaN
[Link](-1) // NaN
parseInt('xyz') // NaN
undefined + 1 // NaN

3.4 Prefix vs Postfix Operators


Operator Behavior

++x (prefix) Increment FIRST, then use value

x++ (postfix) Use value FIRST, then increment

--x (prefix) Decrement FIRST, then use value

x-- (postfix) Use value FIRST, then decrement

📄 [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.1 If-Else Statements


Conditional statements control which block of code executes based on a boolean condition.
📄 [Link]
// Basic if-else
let score = 75;

if (score >= 90) {


[Link]('Grade: A');
} else if (score >= 75) {
[Link]('Grade: B'); // ← This runs
} else if (score >= 60) {
[Link]('Grade: C');
} else {
[Link]('Grade: F');
}

// Nested if (use sparingly — can become unreadable)


let age = 20;
let hasID = true;

if (age >= 18) {


if (hasID) {
[Link]('Entry allowed');
} else {
[Link]('Need ID');
}
}

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.

FALSY Values (evaluate to false) TRUTHY Values (evaluate to true)

false true

0, -0, 0n (BigInt zero) Any non-zero number (1, -1, 3.14)

"" (empty string) Any non-empty string ("0", "false")

null [] (empty array)

undefined {} (empty object)

NaN Any function

(that's all 7 falsy values!) Everything else

📄 [Link]
// Practical truthy/falsy usage
let username = '';

if (username) {
[Link]('Hello, ' + username);
} else {
[Link]('Please enter a username'); // ← runs (empty string is falsy)
}

// Watch out: empty array and object are TRUTHY


let items = [];
if (items) {
[Link]('items exists'); // ← this runs!
}
// Check length instead:
if ([Link] > 0) {
[Link]('has items');
}

4.4 Nullish Coalescing Operator (??)


The ?? operator returns the right-hand value only if the left-hand value is null or undefined. Unlike
||, it does NOT trigger on 0 or empty string.
📄 [Link]
// || triggers on ALL falsy values
let count = 0;
[Link](count || 10); // 10 ← 0 is falsy, so 10 is used (BUG!)

// ?? only triggers on null/undefined


[Link](count ?? 10); // 0 ← 0 is valid, so kept (CORRECT!)

// Perfect for API default values


const data = [Link] ?? 'Not provided';
// If API returns 0, it's preserved. If null/undefined, fallback is used.

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

4.5 Ternary Operator


A concise one-line alternative to if-else. Syntax: condition ? valueIfTrue : valueIfFalse
📄 [Link]
// Classic if-else
let age = 20;
let status;
if (age >= 18) { status = 'Adult'; }
else { status = 'Minor'; }

// Ternary equivalent
let status2 = age >= 18 ? 'Adult' : 'Minor';

// Ternary in JSX (React)


// <div>{isLoggedIn ? <UserPanel /> : <LoginForm />}</div>

// Nested ternary (use carefully — can hurt readability)


let grade = score >= 90 ? 'A' : score >= 75 ? 'B' : score >= 60 ? 'C' : 'F';

💡 SMART TIP: Use ternary for simple yes/no conditions. For 3+ conditions, stick with if-else or
switch for readability.
SECTION 5: Loops & Iteration

5.1 For Loop


The classic for loop runs code a specific number of times. Best when you know exactly how many
iterations you need.
📄 [Link]
// Basic for loop
for (let i = 0; i < 5; i++) {
[Link]('Iteration:', i); // 0, 1, 2, 3, 4
}

// Loop through an array


let fruits = ['apple', 'banana', 'mango'];
for (let i = 0; i < [Link]; i++) {
[Link](fruits[i]);
}

// Reverse loop
for (let i = [Link] - 1; i >= 0; i--) {
[Link](fruits[i]); // mango, banana, apple
}

// Multiplication table (nested loops)


for (let i = 1; i <= 5; i++) {
for (let j = 1; j <= 5; j++) {
[Link](i * j + '\t');
}
[Link]();
}

5.2 While & Do-While Loops


While loops are best when the number of iterations is unknown and depends on a condition.
📄 [Link]
// While loop
let count = 0;
while (count < 5) {
[Link](count);
count++;
}

// Do-while — always executes at least ONCE


let num;
do {
num = [Link]();
[Link]('Generated:', num);
} while (num < 0.5); // Keeps generating until num >= 0.5
// Even if first num >= 0.5, it still runs once

🌍 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
}

// With index using entries()


for (let [index, value] of [Link]()) {
[Link](index, value); // 0 red, 1 green, 2 blue
}

// Map iteration
let map = new Map([['name', 'Ariyan'], ['age', 20]]);
for (let [key, val] of map) {
[Link](key, '->', val);
}

5.4 for...in — Iterating Object Keys


for...in iterates over the KEYS of an object. Do NOT use it for arrays (use for...of instead).
📄 [Link]
let student = { name: 'Ariyan', age: 20, course: 'CST' };

for (let key in student) {


[Link](key + ':', student[key]);
// name: Ariyan
// age: 20
// course: CST
}

// Warning: also iterates inherited properties


// Use hasOwnProperty() to be safe:
for (let key in student) {
if ([Link](key)) {
[Link](key, student[key]);
}
}

⚠️ 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.

5.5 forEach, map, filter, reduce


These are powerful array methods that use a functional programming style. They are the backbone
of modern JavaScript data processing.
📄 [Link]
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// forEach — iterate, no return value


[Link]((num, index) => {
[Link](index, num);
});

// map — transform each element, returns NEW array


let doubled = [Link](num => num * 2);
// [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

// filter — keep elements matching condition, returns NEW array


let evens = [Link](num => num % 2 === 0);
// [2, 4, 6, 8, 10]

// reduce — accumulate to single value


let sum = [Link]((accumulator, current) => accumulator + current, 0);
// 55

// Real-world: shopping cart total


let cart = [
{ item: 'Book', price: 250 },
{ item: 'Pen', price: 30 },
{ item: 'Bag', price: 800 },
];

let total = [Link]((sum, product) => sum + [Link], 0);


[Link]('Total: ₹' + total); // Total: ₹1080

// Chaining — filter then map


let expensiveItems = cart
.filter(p => [Link] > 100)
.map(p => [Link]);
// ['Book', 'Bag']

🌍 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

6.1 Function Declaration vs Expression


Function Declaration Function Expression

function greet() { ... } const greet = function() { ... }

Hoisted — can call before definition NOT hoisted — must define before calling

Named in stack traces Anonymous unless given a name

Good for utility functions Good for callbacks, conditional assignment

📄 [Link]
// Declaration — hoisted
[Link](add(2, 3)); // Works! (hoisted)
function add(a, b) {
return a + b;
}

// Expression — NOT hoisted


// [Link](multiply(2, 3)); // ❌ ReferenceError
const multiply = function(a, b) {
return a * b;
};

6.2 Arrow Functions


Arrow functions (ES6) provide a concise syntax and critically, they do NOT have their own 'this'
binding.
📄 [Link]
// Regular function
function square(x) { return x * x; }

// Arrow function — full syntax


const square = (x) => { return x * x; };

// Arrow function — implicit return (one expression)


const square = x => x * x;

// No parameters
const greet = () => 'Hello!';

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

// Returning an object (wrap in parentheses!)


const makeUser = name => ({ name: name, active: true });

// Arrow function in array methods


let nums = [3, 1, 4, 1, 5];
let sorted = [Link]((a, b) => a - b); // [1, 1, 3, 4, 5]

⚠️ 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'.

6.3 Parameters, Arguments & Rest Operator


📄 [Link]
// Parameters — variable names in function definition
// Arguments — actual values passed when calling

function greet(name, greeting = 'Hello') { // default parameter


return `${greeting}, ${name}!`;
}
greet('Ariyan'); // 'Hello, Ariyan!'
greet('Bob', 'Hi'); // 'Hi, Bob!'

// Rest operator — collect remaining args into array


function sum(...numbers) {
return [Link]((total, n) => total + n, 0);
}
sum(1, 2, 3); // 6
sum(1, 2, 3, 4, 5); // 15 — works with any number of args!

// Mix fixed and rest


function logger(level, ...messages) {
[Link](msg => [Link](`[${level}] ${msg}`));
}
logger('INFO', 'Server started', 'Port: 3000', 'DB connected');

6.4 IIFE — Immediately Invoked Function Expression


An IIFE is a function that runs immediately after it is defined. Used to create a private scope and
avoid polluting the global namespace.
📄 [Link]
// IIFE syntax
(function() {
let privateVar = 'I am private';
[Link](privateVar); // Works
})();

// [Link](privateVar); // ❌ ReferenceError — not accessible outside

// IIFE with arrow function


(() => {
[Link]('IIFE with arrow function');
})();

// IIFE with return value


const result = (function() {
return 42;
})();
[Link](result); // 42
🌍 REAL-WORLD USE: IIFEs were the original module pattern before ES6 modules. Libraries like
jQuery wrapped their entire code in IIFEs to avoid naming conflicts with other scripts on the page.
SECTION 7: Objects In Depth

7.1 Object Literals vs Singleton


Object Literal { } Object via new Object()

Most common approach Rarely used, more verbose

const obj = { key: value } const obj = new Object()

Multiple instances possible Same result, no advantage

Recommended approach Avoid in modern JS

📄 [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)

// Dynamic key access


let key = 'age';
user[key]; // 20 — bracket notation with variable

// 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]

// Swap variables using destructuring


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

🌍 REAL-WORLD USE: Destructuring is used everywhere in React: const { useState, useEffect } =


React; and in API responses: const { data, loading, error } = useQuery().

7.3 Spread & Rest Operators


📄 [Link]
// Spread — expand an iterable into individual elements

// Copy an array
const original = [1, 2, 3];
const copy = [...original];

// Merge arrays
const merged = [...original, ...copy, 4, 5];

// Copy an object (shallow)


const obj1 = { a: 1, b: 2 };
const obj2 = { ...obj1, c: 3 }; // { a: 1, b: 2, c: 3 }

// Override properties
const updated = { ...obj1, b: 99 }; // { a: 1, b: 99 }

// Function call spread


const nums = [1, 2, 3];
[Link]([Link](...nums)); // 3

// Rest in function — collect into array


function logAll(first, ...others) {
[Link]('First:', first);
[Link]('Others:', others);
}
logAll(1, 2, 3, 4); // First: 1, Others: [2, 3, 4]

7.4 JSON API Basics


JSON (JavaScript Object Notation) is the universal data exchange format between clients and
servers. Understanding it is essential for any web developer.
📄 [Link]
// [Link] — convert JS object to JSON string
const user = { name: 'Ariyan', age: 20, active: true };
const jsonString = [Link](user);
// '{"name":"Ariyan","age":20,"active":true}'

// Pretty print JSON


[Link]([Link](user, null, 2));

// [Link] — convert JSON string back to JS object


const parsed = [Link](jsonString);
[Link]([Link]); // 'Ariyan'

// What JSON CANNOT contain:


// - Functions (stripped out)
// - undefined (stripped out)
// - Symbol (stripped out)
// - Circular references (throws error)

🌍 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

8.1 What is Execution Context?


Every time JavaScript runs code, it creates an Execution Context — an environment that contains
all the information needed to execute that code.

Phase What Happens Example

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

Pop from Stack Context removed when function Stack shrinks


returns

📄 [Link]
// Global Execution Context created first
let x = 10; // Memory phase: x = undefined → Exec: x = 10

function outer() { // Memory phase: outer = function reference


let y = 20; // New execution context created when called

function inner() { // inner's execution context on top of stack


let z = 30;
[Link](x + y + z); // 60 — accesses all 3 contexts via scope chain
}

inner(); // inner context pushed, then popped after return


}

outer(); // outer context pushed, then popped

8.2 The Call Stack


The Call Stack is a LIFO (Last In, First Out) data structure that tracks function calls. When a
function is called, it's pushed onto the stack. When it returns, it's popped off.

📄 [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]
}

let result = add(3, 4); // Stack: [global]


[Link](result); // 13
// Stack overflow — infinite recursion
// function infinite() { infinite(); }
// infinite(); // ❌ RangeError: Maximum call stack size exceeded

📌 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

9.1 What is the DOM?


The Document Object Model (DOM) is a tree-like representation of an HTML document. JavaScript
can read and modify any part of this tree — adding, removing, and changing elements and their
properties.

📄 [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
*/

9.2 Selecting Elements


Method Selects Returns

getElementById('id') Single element by ID Element | null

getElementsByClassName('cls') Elements by class HTMLCollection (live)

getElementsByTagName('tag') Elements by tag HTMLCollection (live)

querySelector('.css') First matching element Element | null

querySelectorAll('.css') All matching elements NodeList (static)

📄 [Link]
// getElementById
const title = [Link]('title');
[Link]([Link]); // 'Hello'

// querySelector — most flexible (use CSS selectors)


const firstLi = [Link]('ul li');
const activeBtn = [Link]('[Link]');
const input = [Link]('#email');
// querySelectorAll — returns NodeList (use forEach on it)
const allLi = [Link]('li');
[Link](item => [Link]([Link]));

9.3 Modifying Elements


📄 [Link]
const title = [Link]('h1');

// Change text content


[Link] = 'New Title'; // sets plain text
[Link] = '<em>New</em> Title'; // sets HTML (⚠️ XSS risk with user input!)

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

9.4 Creating & Removing Elements


📄 [Link]
// CREATE a new element
const newDiv = [Link]('div');
[Link] = 'I am new!';
[Link]('card');
[Link]('id', 'card-1');

// INSERT into the DOM


[Link](newDiv); // end of body
[Link](newDiv); // start of body
[Link](newDiv, referenceNode); // before specific element

// Modern insertion methods


[Link](newDiv, 'some text'); // end, accepts multiple
[Link](newDiv); // start
[Link](newDiv); // before reference
[Link](newDiv); // after reference

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

10.1 Adding Event Listeners


Events are things that happen in the browser: clicks, key presses, mouse moves, form submits, etc.
You 'listen' for events and run code when they occur.
📄 [Link]
// Basic event listener
const btn = [Link]('#myBtn');

[Link]('click', function(event) {
[Link]('Button clicked!');
[Link]([Link]); // the element that was clicked
});

// Arrow function handler


[Link]('click', (e) => {
[Link]('Clicked at:', [Link], [Link]); // mouse coordinates
});

// Named function (easier to remove later)


function handleClick(e) {
[Link]([Link]); // 'click'
}
[Link]('click', handleClick);
[Link]('click', handleClick); // Remove by same reference

// Common event types


// click, dblclick, mouseenter, mouseleave, mouseover
// keydown, keyup, keypress
// submit, input, change, focus, blur
// scroll, resize, load, DOMContentLoaded

10.2 Event Object


📄 [Link]
[Link]('keydown', (e) => {
[Link]([Link]); // 'Enter', 'a', 'ArrowUp'
[Link]([Link]); // numeric code (deprecated but used)
[Link]([Link]); // true if Ctrl held
[Link]([Link]); // true if Shift held
[Link]([Link]); // true if Alt held

if ([Link] === 'Enter') {


[Link]('Enter pressed!');
}
});

// 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);
});

10.3 Event Bubbling & Capturing


When an event occurs on an element, it travels through the DOM in two phases: Capturing (top-
down) and Bubbling (bottom-up).

Event Bubbling (default) Event Capturing (opt-in)

Event starts at target element Event starts at window/document

Travels UP through ancestors Travels DOWN to target

Default behavior (3rd arg: false) Use 3rd arg: true to enable

Most events use bubbling Used for very specific scenarios

stopPropagation() stops it stopPropagation() stops it too

📄 [Link]
<div id='outer'>
<div id='inner'>
<button id='btn'>Click me</button>
</div>
</div>

// All three will fire when button is clicked (bubbling order):


// btn → inner → outer
[Link]('#btn').addEventListener('click', () =>
[Link]('Button'));
[Link]('#inner').addEventListener('click', () =>
[Link]('Inner'));
[Link]('#outer').addEventListener('click', () =>
[Link]('Outer'));

// Stop bubbling
[Link]('#btn').addEventListener('click', (e) => {
[Link](); // Only 'Button' logs, inner and outer won't fire
[Link]('Button');
});

10.4 Event Delegation


Instead of attaching listeners to each child element, attach ONE listener to the parent and use
[Link] to determine which child was clicked.
📄 [Link]
// Without delegation — BAD (adds many listeners)
[Link]('li').forEach(li => {
[Link]('click', () => [Link]([Link]));
});

// 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');
}
});

// This even works for dynamically added li elements!

🌍 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

11.1 Lexical Scoping


Lexical scope means: a function's scope is determined by WHERE it is WRITTEN in the code, not
where it is called from.
📄 [Link]
let globalVar = 'I am global';

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
}

// [Link](outerVar); // ❌ not accessible here

11.2 What is a Closure?


A closure is a function that REMEMBERS the variables from its lexical scope even after the outer
function has finished executing. The inner function 'closes over' its environment.
📄 [Link]
function makeCounter() {
let count = 0; // ← 'count' is in closure

return {
increment() { count++; },
decrement() { count--; },
getCount() { return count; }
};
}

const counter = makeCounter();


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

// count is PRIVATE — no one can directly access or modify it


// [Link](count); // ❌ ReferenceError

// Each call to makeCounter() creates a SEPARATE closure


const counter2 = makeCounter();
[Link]();
[Link]([Link]()); // 1 (independent of counter)

11.3 Practical Closure Patterns


📄 [Link]
// 1. Memoization — cache function results
function memoize(fn) {
const cache = {}; // ← cache lives in closure
return function(...args) {
const key = [Link](args);
if (cache[key] !== undefined) {
[Link]('From cache!');
return cache[key];
}
cache[key] = fn(...args);
return cache[key];
};
}

const slowSquare = (n) => { /* imagine slow computation */ return n * n; };


const fastSquare = memoize(slowSquare);
fastSquare(5); // computed
fastSquare(5); // 'From cache!' — instant

// 2. Once function — run only once


function once(fn) {
let called = false;
return function(...args) {
if (!called) {
called = true;
return fn(...args);
}
};
}

const initDB = once(() => [Link]('DB initialized!'));


initDB(); // 'DB initialized!'
initDB(); // Nothing — already ran

🌍 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

12.1 Prototypal Inheritance


Every JavaScript object has an internal link to another object called its prototype. When you access
a property, JavaScript first looks at the object, then at its prototype, then the prototype's prototype
— all the way up the prototype chain until null.
📄 [Link]
// Object prototype chain
const animal = {
breathe() { return 'Breathing...'; }
};

const dog = [Link](animal); // dog's prototype = animal


[Link] = function() { return 'Woof!'; };

[Link]([Link]()); // 'Woof!' — own property


[Link]([Link]()); // 'Breathing...' — inherited from animal!

// Check the chain


[Link]([Link](dog) === animal); // true

// hasOwnProperty — check if property is own, not inherited


[Link]([Link]('bark')); // true
[Link]([Link]('breathe')); // false — inherited

12.2 ES6 Classes


Classes in JavaScript are syntactic sugar over prototypal inheritance. Under the hood, classes still
use prototypes — the class syntax just looks cleaner.
📄 [Link]
class User {
// Static property — belongs to class, not instances
static userCount = 0;

constructor(name, email) {
[Link] = name;
[Link] = email;
[Link]++;
}

// Instance method
greet() {
return `Hello, I'm ${[Link]}`;
}

// Static method — call on class, not instance


static getCount() {
return [Link];
}
}
const user1 = new User('Ariyan', 'a@[Link]');
const user2 = new User('Bob', 'b@[Link]');

[Link]([Link]()); // 'Hello, I'm Ariyan'


[Link]([Link]()); // 2
// [Link]([Link]()); // ❌ TypeError — static methods on class

12.3 Inheritance with extends


📄 [Link]
class Animal {
constructor(name) {
[Link] = name;
}
speak() {
return `${[Link]} makes a sound.`;
}
}

class Dog extends Animal {


constructor(name, breed) {
super(name); // ← MUST call super() first to initialize Animal
[Link] = breed;
}

speak() { // Override parent method


return `${[Link]} barks!`;
}

info() {
return `${[Link]()} — Breed: ${[Link]}`; // call parent method
}
}

const dog = new Dog('Rex', 'Labrador');


[Link]([Link]()); // 'Rex barks!'
[Link]([Link]()); // 'Rex makes a sound. — Breed: Labrador'

12.4 Getters & Setters


Getters and setters let you define special methods that look like properties when accessed. They
enable controlled access and validation.
📄 [Link]
class Temperature {
constructor(celsius) {
this._celsius = celsius; // _ convention = 'private'
}

// Getter — access as property, not method


get fahrenheit() {
return this._celsius * 9/5 + 32;
}

// Setter — with validation


set celsius(value) {
if (value < -273.15) {
throw new Error('Below absolute zero!');
}
this._celsius = value;
}
get celsius() { return this._celsius; }
}

const temp = new Temperature(100);


[Link]([Link]); // 212 ← accessed like a property!
[Link] = 0;
[Link]([Link]); // 32
// [Link] = -300; // ❌ Error: Below absolute zero!

🌍 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

13.1 The JavaScript Event Loop


JavaScript is single-threaded — it can only do one thing at a time. But it handles async operations
(API calls, timers) via the Event Loop.

Component What it does Example

Call Stack Executes synchronous code function calls

Web APIs Handles async tasks outside JS setTimeout, fetch, DOM events

Callback Queue Holds callbacks ready to run setTimeout callbacks

Microtask Queue Higher priority than Callback Q Promise callbacks

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

// Output order: Start → End → Promise → Timeout

📌 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
});

13.3 Promise Combinators


📄 [Link]
const p1 = new Promise(res => setTimeout(() => res('P1'), 1000));
const p2 = new Promise(res => setTimeout(() => res('P2'), 500));
const p3 = new Promise((_, rej) => setTimeout(() => rej('P3 failed'), 800));

// [Link] — waits for ALL, fails if ANY rejects


[Link]([p1, p2]).then(values => {
[Link](values); // ['P1', 'P2'] after 1000ms
});

// [Link] — waits for ALL regardless of outcome


[Link]([p1, p2, p3]).then(results => {
[Link](r => [Link]([Link], [Link] || [Link]));
});

// [Link] — resolves/rejects with FIRST settled promise


[Link]([p1, p2]).then(val => [Link](val)); // 'P2' (fastest)

// [Link] — resolves with FIRST FULFILLED (ignores rejects)


[Link]([p3, p1, p2]).then(val => [Link](val)); // 'P2'

13.4 Fetch API & Async/Await


📄 [Link]
// Fetch API — modern way to make HTTP requests
fetch('[Link]
.then(response => {
if (![Link]) throw new Error('HTTP error! Status: ' + [Link]);
return [Link](); // Parse JSON — returns another Promise
})
.then(data => {
[Link]([Link], [Link]);
})
.catch(err => [Link]('Fetch failed:', err));
// ─────────────────────────────────────────────
// Async/Await — cleaner syntax for same thing
// ─────────────────────────────────────────────
async function getUser(username) {
try {
const response = await fetch(`[Link]

if (![Link]) {
throw new Error(`HTTP ${[Link]}`);
}

const data = await [Link]();


[Link](`Name: ${[Link]}`);
[Link](`Repos: ${data.public_repos}`);
return data;

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

Project 1 — Color Switcher


Concept demonstrated: DOM selection, event listeners, dynamic style changes, array iteration.
📄 [Link]
// HTML structure assumed:
// <button data-color='red'>Red</button>
// <button data-color='green'>Green</button>
// <button data-color='blue'>Blue</button>
// <button id='reset'>Reset</button>

const buttons = [Link]('button[data-color]');


const resetBtn = [Link]('#reset');

// Event delegation on parent instead of each button


[Link]('.color-btns').addEventListener('click', (e) => {
const color = [Link];
if (color) {
[Link] = color;
}
});

[Link]('click', () => {
[Link] = '';
});

Project 2 — BMI Calculator


Concept demonstrated: Form input reading, numeric parsing, conditional logic, DOM updates.
📄 [Link]
// HTML: <input id='weight'>, <input id='height'>, <button>, <div id='result'>

[Link]('#calcBtn').addEventListener('click', () => {
const weight = parseFloat([Link]('#weight').value);
const height = parseFloat([Link]('#height').value) / 100; // cm
to m

if (isNaN(weight) || isNaN(height) || weight <= 0 || height <= 0) {


[Link]('#result').textContent = 'Please enter valid values!';
return;
}

const bmi = (weight / (height * height)).toFixed(2);

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}`;
});

Project 3 — Number Guessing Game


Concept demonstrated: Random numbers, state management, conditional feedback, attempt
tracking.
📄 [Link]
const secret = [Link]([Link]() * 100) + 1; // 1–100
let attemptsLeft = 10;
const prevGuesses = [];

[Link]('#guessBtn').addEventListener('click', () => {
const guess = parseInt([Link]('#guessInput').value);

if (isNaN(guess) || guess < 1 || guess > 100) {


showMsg('Enter a number between 1 and 100!', 'error');
return;
}

[Link](guess);
attemptsLeft--;

if (guess === secret) {


showMsg(`🎉 Correct! The number was ${secret}`, 'success');
[Link]('#guessBtn').disabled = true;
} else if (attemptsLeft === 0) {
showMsg(`Game over! The number was ${secret}`, 'error');
[Link]('#guessBtn').disabled = true;
} else if (guess < secret) {
showMsg(`Too low! ${attemptsLeft} attempts left`, 'hint');
} else {
showMsg(`Too high! ${attemptsLeft} attempts left`, 'hint');
}

[Link]('#previous').textContent =
'Previous: ' + [Link](', ');
});

function showMsg(msg, type) {


const el = [Link]('#message');
[Link] = msg;
[Link] = type; // CSS classes for colors
}

Project 4 — Digital Clock


Concept demonstrated: Date object, setInterval, live DOM updates, time formatting.
📄 [Link]
function updateClock() {
const now = new Date();
// Get time components with leading zeros
const hours = String([Link]()).padStart(2, '0');
const minutes = String([Link]()).padStart(2, '0');
const seconds = String([Link]()).padStart(2, '0');

// Format the date


const dateStr = [Link]('en-IN', {
weekday: 'long', year: 'numeric',
month: 'long', day: 'numeric'
});

// Update DOM
[Link]('#time').textContent = `${hours}:${minutes}:${seconds}`;
[Link]('#date').textContent = dateStr;
}

// Call immediately (no 1-second delay on first load)


updateClock();

// Update every 1000ms (1 second)


const clockInterval = setInterval(updateClock, 1000);

// Stop clock (call when page unloads)


// clearInterval(clockInterval);

🌍 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

15.1 Date Object


📄 [Link]
// Create dates
const now = new Date(); // Current date/time
const d1 = new Date('2024-01-15'); // From ISO string
const d2 = new Date(2024, 0, 15, 10, 30); // Year, month (0-indexed!), day,
hrs, min
const epoch = new Date(0); // Unix epoch: Jan 1 1970

// 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'

// Date math (in milliseconds)


const oneWeekLater = new Date([Link]() + 7 * 24 * 60 * 60 * 1000);

⚠️ WARNING: Months are 0-indexed (0=January, 11=December). This trips up almost every
developer at least once!

15.2 String Methods


📄 [Link]
const str = ' Hello, JavaScript World! ';

[Link](); // 'Hello, JavaScript World!' — remove whitespace


[Link](); // ' HELLO, JAVASCRIPT WORLD! '
[Link](); // ' hello, javascript world! '
[Link]('Java'); // true
[Link](' He'); // true
[Link]('! '); // true
[Link]('Java'); // 8 (index of first occurrence)
[Link](7, 17); // 'JavaScript'
[Link]('Hello', 'Hi'); // ' Hi, JavaScript World! '
[Link]('l', 'L'); // replaces ALL occurrences
[Link](', '); // [' Hello', 'JavaScript World! ']
[Link](' ').join('-'); // converts spaces to hyphens

// Template literals (ES6)


const name = 'Ariyan';
const age = 20;
`Name: ${name}, Age: ${age}`; // 'Name: Ariyan, Age: 20'
`${2 + 2} is four`; // '4 is four' — any expression works

15.3 Math Object


📄 [Link]
[Link]; // 3.141592653589793
Math.E; // 2.718281828459045

[Link](-5); // 5 — absolute value


[Link](4.1); // 5 — round UP
[Link](4.9); // 4 — round DOWN
[Link](4.5); // 5 — round to nearest
[Link](4.9); // 4 — remove decimal, no rounding

[Link](1, 5, 3); // 5
[Link](1, 5, 3); // 1
[Link](2, 8); // 256
[Link](144); // 12

[Link](); // 0.0 to 0.999...


[Link]([Link]() * 10); // 0 to 9
[Link]([Link]() * 10) + 1; // 1 to 10

// Random number in range [min, max]


function random(min, max) {
return [Link]([Link]() * (max - min + 1)) + min;
}
random(1, 100); // random int from 1 to 100
SECTION 16: Interview Q&A & Quick Reference

16.1 Top 25 JavaScript Interview Questions

▶ Q1: What is the difference between var, let, and const?


var is function-scoped and hoisted (initialized as undefined). let and const are block-scoped and not
initialized in the TDZ (Temporal Dead Zone). const cannot be reassigned but its object properties
can be mutated. Always prefer const > let > var.

▶ Q2: What is hoisting?


Hoisting is JavaScript's behavior of moving declarations to the top of their scope during the memory
(creation) phase. Function declarations are fully hoisted (can be called before declaration). var
variables are hoisted but initialized as undefined. let and const are in the Temporal Dead Zone until
their declaration line.

▶ Q3: Explain closures with an example.


A closure is a function that retains access to its outer function's variables even after the outer
function has completed execution. Example: a counter factory where the count variable is private
but accessible via returned functions.

▶ Q4: What is the difference between == and ===?


== performs type coercion before comparing (0 == '0' is true). === is strict equality — compares
both value AND type without coercion (0 === '0' is false). Always use === in production code.

▶ Q5: What is the event loop?


The event loop is the mechanism that allows JavaScript to perform non-blocking async operations
despite being single-threaded. It continuously checks the call stack and moves callbacks from the
microtask queue (Promises) and callback queue (setTimeout) to the stack when it's empty.
Microtask queue has higher priority than callback queue.

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

▶ Q8: What is event delegation?


Event delegation is attaching a single event listener to a parent element instead of multiple listeners
to each child. Use [Link] to identify which child was clicked. Benefits: fewer event listeners in
memory, works for dynamically added elements.

▶ Q9: What is the difference between null and undefined?


undefined means a variable has been declared but not yet assigned a value (JavaScript sets it).
null is an intentional assignment meaning 'no value' or 'empty' (developer sets it). typeof null ===
'object' is a known bug. null == undefined is true but null === undefined is false.

▶ Q10: How does prototypal inheritance work?


Every JS object has an internal [[Prototype]] reference. When accessing a property, JS looks at the
object first, then traverses the prototype chain until it finds it or reaches null. [Link]() sets
the prototype. ES6 classes are syntactic sugar over this mechanism.

▶ Q11: What is 'this' in JavaScript?


'this' refers to the execution context. In global scope: the window/global object. In a method: the
object before the dot. In arrow functions: 'this' is lexically inherited from the enclosing context (no
own 'this'). In strict mode global 'this' is undefined. call(), apply(), bind() can explicitly set 'this'.

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

▶ Q13: What is an IIFE?


An Immediately Invoked Function Expression is a function that runs immediately after it is defined.
Syntax: (function(){})() or (() => {})(). Used to create private scope, avoid polluting global
namespace. Was the original module pattern before ES6 modules.
▶ Q14: What are truthy and falsy values?
Falsy values (there are only 7): false, 0, -0, 0n, '' (empty string), null, undefined, NaN. Everything
else is truthy, including '0', 'false', [], and {}. Used in conditional checks without explicit comparison.

▶ Q15: Explain map(), filter(), and reduce().


map() transforms each element and returns a NEW array of same length. filter() keeps elements
matching a condition and returns a NEW array (possibly shorter). reduce() accumulates all
elements into a single value. All three are pure — they don't modify the original array.

16.2 Cheat Sheet — Key Syntax

📄 [Link]
// ── Variables ─────────────────────────────────────────
const PI = 3.14; // Block-scoped, no reassign
let count = 0; // Block-scoped, reassignable

// ── Arrow Functions ───────────────────────────────────


const add = (a, b) => a + b;
const greet = name => `Hello, ${name}!`;
const getObj = () => ({ key: 'value' });

// ── 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); }
}

// ── Optional Chaining (?.) ────────────────────────────


const city = user?.address?.city ?? 'Unknown';

// ── Class ─────────────────────────────────────────────
class Animal {
#name; // Private field (ES2022)
constructor(name) { this.#name = name; }
get name() { return this.#name; }
}

16.3 Common Mistakes to Avoid


Mistake Why It's Wrong Correct Approach

Using var Function-scoped, redeclarable, Use const/let


hoisting issues

== instead of === Type coercion causes Always use ===


unexpected results

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

for...in on arrays Iterates prototype properties too Use for...of or forEach

Forgetting 'return' in reduce Accumulator becomes Always return accumulator


undefined

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

17.1 ES6+ Features Summary

Feature Syntax Purpose

Template Literals `Hello ${name}` String interpolation

Destructuring const {a, b} = obj Extract properties

Spread Operator [...arr] {...obj} Copy/merge arrays & objects

Arrow Functions (x) => x * 2 Concise functions, lexical this

Default Parameters fn(x, y=10) Default argument values

Rest Parameters fn(...args) Collect extra arguments

Optional Chaining obj?.prop?.method?.() Safe property access

Nullish Coalescing value ?? 'default' Fallback for null/undefined

Modules (import/export) import { fn } from './file' Code splitting

Classes class Animal extends Base OOP syntax

Promises / async-await async fn() { await ... } Async operations

Symbol Symbol('description') Unique identifiers

BigInt 9999999999999999999n Large integers

Map & Set new Map(), new Set() Advanced data structures

17.2 What to Learn Next


• Advanced Array Methods: flat(), flatMap(), [Link](), [Link]()
• Generators & Iterators: function*, yield — for lazy evaluation and custom iterables
• WeakMap & WeakSet — memory-efficient collections for private data
• Proxy & Reflect — intercept and redefine fundamental operations on objects
• Web Workers — run JavaScript in background threads
• Service Workers & PWA — offline-capable web applications
• Module system: ES Modules (import/export) vs CommonJS (require/[Link])
• TypeScript — typed superset of JavaScript for large-scale development

17.3 Recommended Learning Path

Phase Focus Projects to Build


Phase 1 (Now) JS Fundamentals (this series) Color switcher, BMI calc,
Guessing game

Phase 2 DOM & Events mastery Todo app, Quiz app, Form
validator

Phase 3 Async JS & APIs Weather app, GitHub profile


viewer

Phase 4 [Link] & Express REST API, Auth system

Phase 5 React/[Link] Full-stack web apps

Phase 6 Advanced patterns System design, optimization

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

Keep Coding, Keep Learning. You've Got This! 🚀

You might also like