JavaScript
Complete Notes & Reference Guide
From Fundamentals to OOP, Async & DOM
Topics Covered
• Variables, Data Types & Operators
• Strings & Template Literals
• Arrays & Array Methods
• Functions, Scope & Closures
• Objects & Prototypes
• Control Flow & Loops
• Higher-Order Functions (map, filter, reduce, ...)
• ES6+ Features (Spread, Rest, Destructuring)
• The DOM & Events
• Asynchronous JS (Callbacks, Promises, Async/Await)
• APIs, JSON & Fetch
• OOP: Classes, Inheritance & Prototypes
• Error Handling
• JavaScript Engine & Event Loop
Table of Contents
Table of Contents ............................................................................................................................................ 1
1. Variables & Data Types ................................................................................................................................ 4
1.1 Variable Declarations: let, const, var ...................................................................................................... 4
Variable Naming Rules ............................................................................................................................. 5
1.2 Primitive Data Types .............................................................................................................................. 5
1.3 Reference Types..................................................................................................................................... 5
1.4 typeof Operator ..................................................................................................................................... 6
1.5 NaN — Not a Number ............................................................................................................................ 6
2. Operators .................................................................................................................................................... 6
2.1 Arithmetic Operators ............................................................................................................................. 6
Operator Precedence (high to low) .......................................................................................................... 7
2.2 Assignment Operators ........................................................................................................................... 7
2.3 Comparison Operators ........................................................................................................................... 7
2.4 Logical Operators ................................................................................................................................... 7
2.5 Unary Operators: ++ and -- ..................................................................................................................... 8
3. Strings ......................................................................................................................................................... 8
3.1 String Basics ........................................................................................................................................... 9
3.2 Essential String Methods ........................................................................................................................ 9
4. Arrays ........................................................................................................................................................ 10
4.1 Adding & Removing Elements .............................................................................................................. 10
4.2 Searching & Testing.............................................................................................................................. 10
4.3 Transforming Arrays............................................................................................................................. 10
4.4 Sorting & Reversing .............................................................................................................................. 11
4.5 slice, concat, spread ............................................................................................................................. 11
5. Control Flow .............................................................................................................................................. 12
5.1 if / else if / else .................................................................................................................................... 12
5.2 switch .................................................................................................................................................. 12
5.3 Loops ................................................................................................................................................... 12
for loop .................................................................................................................................................. 12
for...of (iterable: arrays, strings, maps)................................................................................................... 13
for...in (object keys) ............................................................................................................................... 13
while loop .............................................................................................................................................. 13
break & continue ................................................................................................................................... 13
6. Functions ................................................................................................................................................... 14
6.1 Function Declaration ............................................................................................................................ 14
6.2 Function Expression ............................................................................................................................. 14
6.3 Arrow Functions (ES6) .......................................................................................................................... 14
6.4 Parameters & Arguments ..................................................................................................................... 15
6.5 Scope ................................................................................................................................................... 15
6.6 Closures ............................................................................................................................................... 15
7. Objects ...................................................................................................................................................... 16
7.1 Object Literals ...................................................................................................................................... 16
7.2 this in Objects ...................................................................................................................................... 17
7.3 Iterating Over Objects .......................................................................................................................... 17
7.4 Nested Objects & Array of Objects ....................................................................................................... 17
7.5 Math Object ......................................................................................................................................... 18
8. ES6+ Features ............................................................................................................................................ 18
8.1 Spread Operator (...) ............................................................................................................................ 18
8.2 Rest Parameters (...)............................................................................................................................. 19
8.3 Destructuring ....................................................................................................................................... 19
Array Destructuring ............................................................................................................................... 19
Object Destructuring .............................................................................................................................. 19
8.4 Short-Circuit & Logical Assignment....................................................................................................... 19
9. Higher-Order Functions ............................................................................................................................. 20
9.1 forEach, map, filter, reduce .................................................................................................................. 20
9.2 setTimeout & setInterval ...................................................................................................................... 21
10. Error Handling ......................................................................................................................................... 21
11. DOM Manipulation .................................................................................................................................. 22
11.1 Selecting Elements ............................................................................................................................. 22
11.2 Reading & Modifying Content ............................................................................................................ 22
11.3 classList .............................................................................................................................................. 23
11.4 Creating & Removing Elements .......................................................................................................... 23
11.5 Navigating the DOM Tree ................................................................................................................... 24
12. DOM Events ............................................................................................................................................. 24
12.1 addEventListener ............................................................................................................................... 24
12.2 Common Events ................................................................................................................................. 24
12.3 The Event Object ................................................................................................................................ 25
12.4 Event Bubbling & Delegation .............................................................................................................. 25
13. JavaScript Engine & Event Loop ................................................................................................................ 26
13.1 How Code Executes ............................................................................................................................ 26
13.2 The Event Loop .................................................................................................................................. 26
14. Asynchronous JavaScript .......................................................................................................................... 27
14.1 Callback Hell....................................................................................................................................... 27
14.2 Promises ............................................................................................................................................ 27
14.3 async / await ...................................................................................................................................... 28
14.4 [Link] & [Link]......................................................................................................... 28
15. APIs, JSON & Fetch ................................................................................................................................... 29
15.1 What is an API? .................................................................................................................................. 29
HTTP Status Code Groups....................................................................................................................... 29
15.2 JSON .................................................................................................................................................. 29
15.3 Fetch API ............................................................................................................................................ 30
15.4 URL Structure ..................................................................................................................................... 30
16. Object-Oriented Programming (OOP) ....................................................................................................... 31
16.1 Why OOP? ......................................................................................................................................... 31
16.2 Prototypes ......................................................................................................................................... 31
16.3 Constructor Functions (Pre-ES6) ......................................................................................................... 31
16.4 ES6 Classes ......................................................................................................................................... 32
16.5 Inheritance with extends & super ....................................................................................................... 32
16.6 Private Fields (ES2022) ....................................................................................................................... 33
16.7 Four Pillars of OOP ............................................................................................................................. 34
17. Quick Reference Cheat Sheet ................................................................................................................... 34
Variable Declarations ................................................................................................................................. 34
Arrow Functions ........................................................................................................................................ 34
Destructuring ............................................................................................................................................. 35
Spread & Rest ............................................................................................................................................ 35
Promises & async/await............................................................................................................................. 35
Classes ....................................................................................................................................................... 35
Array Methods Summary ........................................................................................................................... 35
1. Variables & Data Types
In JavaScript, variables are named storage locations that hold values. JS is dynamically typed — you don't
declare the type; the engine figures it out at runtime.
1.1 Variable Declarations: let, const, var
Keyword Description
let Block-scoped. Can be reassigned. Preferred for mutable values.
const Block-scoped. Cannot be reassigned. Preferred for fixed references.
Keyword Description
var Function/globally scoped. Hoisted. Avoid in modern JS.
let name = 'Alice'; // reassignable
const PI = 3.14159; // constant — reassignment throws TypeError
var score = 100; // old style, avoid
// const with objects: reference is fixed, but properties can change
const user = { name: 'Bob' };
[Link] = 'Charlie'; // OK — mutating the object
// user = {}; // TypeError — reassigning the reference
Variable Naming Rules
• Must start with a letter, underscore (_), or dollar sign ($).
• Cannot start with a number.
• Case-sensitive: myVar and myvar are different variables.
• Use camelCase by convention: firstName, totalAmount.
1.2 Primitive Data Types
Type Description & Example
Number Integers and floats: 42, 3.14, -7, Infinity, NaN
String Sequence of characters: 'hello', "world", `template`
Boolean true or false
null Intentional absence of a value. typeof null === 'object' (quirk)
undefined Variable declared but not assigned. Also missing object keys.
Symbol Unique, immutable identifier. Symbol('id') !== Symbol('id')
BigInt Arbitrary-precision integer: 9007199254740991n
1.3 Reference Types
Type Description
Object Collection of key-value pairs: { name: 'Alice', age: 25 }
Array Ordered list of values (special object): [1, 'two', true]
Function Callable object that encapsulates executable code
// Primitive vs Reference — key difference
let a = 5;
let b = a; // b gets a COPY
b = 10;
[Link](a); // 5 — unchanged
let arr1 = [1, 2, 3];
let arr2 = arr1; // arr2 points to SAME array in memory
arr2[0] = 99;
[Link](arr1); // [99, 2, 3] — arr1 is also changed!
💡 Use the spread operator [...arr1] or [...obj] to create shallow copies of arrays and objects,
avoiding this mutation issue.
1.4 typeof Operator
[Link](typeof 42); // 'number'
[Link](typeof 'hello'); // 'string'
[Link](typeof true); // 'boolean'
[Link](typeof undefined); // 'undefined'
[Link](typeof null); // 'object' ← known JS bug
[Link](typeof {}); // 'object'
[Link](typeof []); // 'object' ← arrays are objects
[Link](typeof function(){}); // 'function'
1.5 NaN — Not a Number
NaN is a special Number value that arises from invalid arithmetic operations. It is the only value in JS that is
not equal to itself.
[Link](0 / 0); // NaN
[Link]('abc' * 2); // NaN
[Link](typeof NaN); // 'number' ← NaN is of type number
[Link](NaN === NaN); // false ← unique property
[Link](isNaN('hello')); // true
[Link]([Link](NaN)); // true ← more reliable
2. Operators
2.1 Arithmetic Operators
5 + 3 // 8 — Addition
5 - 3 // 2 — Subtraction
5 * 3 // 15 — Multiplication
10 / 4 // 2.5 — Division
10 % 3 // 1 — Modulus (remainder)
2 ** 8 // 256 — Exponentiation (ES7)
Operator Precedence (high to low)
1. Parentheses ()
2. Exponentiation ** (right-to-left)
3. * / % (left-to-right)
4. + - (left-to-right)
2.2 Assignment Operators
let x = 10;
x += 5; // x = x + 5 → 15
x -= 3; // x = x - 3 → 12
x *= 2; // x = x * 2 → 24
x /= 4; // x = x / 4 → 6
x %= 4; // x = x % 4 → 2
x **= 3; // x = x ** 3 → 8
2.3 Comparison Operators
// Loose equality (type coercion)
5 == '5' // true — '5' is coerced to 5
0 == false // true
// Strict equality (no coercion) — always prefer ===
5 === '5' // false — different types
5 === 5 // true
// Inequality
5 != '5' // false — coercion makes them equal
5 !== '5' // true — strict
// Relational
5 > 3 // true
5 >= 5 // true
3 < 5 // true
3 <= 3 // true
// String comparison: uses Unicode values
'a' < 'b' // true (97 < 98)
'A' < 'a' // true (65 < 97)
💡 Always use === (strict equality) over == to avoid unexpected type coercion bugs.
2.4 Logical Operators
true && false // false — AND: both must be true
true || false // true — OR: at least one true
!true // false — NOT: negation
// Short-circuit evaluation
null && 'hello' // null (stops at null)
'hello' || 'bye' // 'hello' (stops at first truthy)
// Nullish coalescing (ES2020) — only null/undefined triggers fallback
null ?? 'default' // 'default'
0 ?? 'default' // 0 (0 is not null/undefined)
// Optional chaining (ES2020)
const user = null;
user?.name // undefined (no error)
2.5 Unary Operators: ++ and --
let x = 5;
// Prefix: increment FIRST, then use the value
[Link](++x); // 6 (x is now 6)
// Postfix: use the value FIRST, then increment
[Link](x++); // 6 (x becomes 7 after)
[Link](x); // 7
let y = 10;
[Link](--y); // 9 (prefix decrement)
[Link](y--); // 9 (postfix decrement, y becomes 8 after)
3. Strings
Strings are immutable sequences of characters. You can create them with single quotes, double quotes, or
backticks (template literals).
let s1 = 'single quotes';
let s2 = "double quotes";
let s3 = `backtick template literal`;
// Mixing quotes to avoid escaping
let s4 = "He said 'I am going home'";
let s5 = 'She replied "exactly right"';
// Template literals support expressions and multi-line
const name = 'Alice';
const age = 30;
const msg = `Hello, my name is ${name} and I am ${age} years old.`;
// Multi-line:
const html = `
<div>
<p>${name}</p>
</div>
`;
3.1 String Basics
const str = 'Hello, World!';
[Link]([Link]); // 13
[Link](str[0]); // 'H' (index from 0)
[Link]([Link](7)); // 'W'
// Strings are immutable — methods return new strings
str[0] = 'J'; // silently fails in non-strict mode
3.2 Essential String Methods
Method What it does
[Link]() 'hello' → 'HELLO'
[Link]() 'HELLO' → 'hello'
[Link]() Removes whitespace from both ends
[Link]() / trimEnd() Removes whitespace from one end
[Link]('x') First index of 'x', or -1 if not found
[Link]('x') Last index of 'x'
[Link]('x') Returns true/false
[Link]('x') Returns true/false
[Link]('x') Returns true/false
[Link](start, end) Extract substring (end exclusive, supports negative indices)
[Link](start,end) Like slice but no negatives
[Link](delimiter) Split into array: 'a,b,c'.split(',') → ['a','b','c']
[Link]('a','b') Replace first occurrence
[Link]('a','b') Replace all occurrences
[Link](n) Repeat string n times
[Link](len,'x') Pad beginning: '5'.padStart(3,'0') → '005'
[Link](len,'x') Pad end
[Link](s2) Concatenate — prefer template literals or +
const s = ' Hello, World! ';
[Link]([Link]()); // 'Hello, World!'
[Link]([Link]().toLowerCase()); // 'hello, world!'
const csv = 'apple,banana,cherry';
const fruits = [Link](','); // ['apple', 'banana', 'cherry']
[Link]('hello'.slice(1, 3)); // 'el'
[Link]('hello'.slice(-3)); // 'llo' (negative = from end)
4. Arrays
Arrays are ordered, zero-indexed, mutable collections that can hold values of any type, including other arrays
and objects.
const fruits = ['apple', 'banana', 'cherry'];
[Link](fruits[0]); // 'apple'
[Link]([Link]); // 3
fruits[1] = 'blueberry'; // Mutate element
4.1 Adding & Removing Elements
const arr = [1, 2, 3];
// End
[Link](4); // [1,2,3,4] — adds to end, returns new length
[Link](); // [1,2,3] — removes from end, returns removed item
// Beginning
[Link](0); // [0,1,2,3] — adds to start, returns new length
[Link](); // [1,2,3] — removes from start, returns removed item
// splice(start, deleteCount, ...items) — modify in place
[Link](1, 1); // [1,3] — remove 1 element at index 1
[Link](1, 0, 99, 100); // [1,99,100,3] — insert without removing
4.2 Searching & Testing
const nums = [10, 20, 30, 20];
[Link](20); // 1 — first occurrence
[Link](20); // 3 — last occurrence
[Link](30); // true
[Link](n => n > 15); // 20 — first match
[Link](n => n > 15); // 1 — index of first match
4.3 Transforming Arrays
const nums = [1, 2, 3, 4, 5];
// forEach — iterate (no return value)
[Link](n => [Link](n * 2));
// map — transform, returns NEW array
const doubled = [Link](n => n * 2); // [2,4,6,8,10]
// filter — keep matching items, returns NEW array
const evens = [Link](n => n % 2 === 0); // [2,4]
// reduce — accumulate to single value
const sum = [Link]((acc, curr) => acc + curr, 0); // 15
// find — first item that matches
const found = [Link](n => n > 3); // 4
// every — true if ALL pass the test
[Link](n => n > 0); // true
// some — true if AT LEAST ONE passes
[Link](n => n > 4); // true
// flat & flatMap
[[1,2],[3,4]].flat(); // [1,2,3,4]
[1,2,3].flatMap(n => [n, n * 2]); // [1,2,2,4,3,6]
💡 map, filter, and reduce are the three most important array methods. They don't mutate the
original array — they return new ones.
4.4 Sorting & Reversing
const arr = [3, 1, 4, 1, 5, 9];
[Link](); // [1,1,3,4,5,9] — works for strings!
// For numbers, ALWAYS use a comparator:
[Link]((a, b) => a - b); // ascending
[Link]((a, b) => b - a); // descending
[Link](); // reverses in-place, returns the array
4.5 slice, concat, spread
const arr = [1, 2, 3, 4, 5];
// slice(start, end) — returns new array, non-destructive
[Link](1, 3); // [2, 3]
[Link](-2); // [4, 5]
[Link](); // shallow copy of entire array
// concat — join arrays, returns new array
[1,2].concat([3,4], [5]); // [1,2,3,4,5]
// Spread — modern preferred way
const combined = [...arr, ...arr]; // [1,2,3,4,5,1,2,3,4,5]
5. Control Flow
5.1 if / else if / else
const age = 20;
if (age < 13) {
[Link]('Child');
} else if (age < 18) {
[Link]('Teenager');
} else if (age < 65) {
[Link]('Adult');
} else {
[Link]('Senior');
}
// Ternary operator — shorthand if/else
const label = age >= 18 ? 'Adult' : 'Minor';
5.2 switch
const day = 'Monday';
switch (day) {
case 'Monday':
[Link]('Start of work week');
break; // Without break, falls through to next case!
case 'Friday':
[Link]('Almost weekend');
break;
case 'Saturday':
case 'Sunday':
[Link]('Weekend!'); // Shared handler for two cases
break;
default:
[Link]('Midweek');
}
💡 Always include break after each case, unless you intentionally want fall-through. Forgetting
break is a common bug.
5.3 Loops
for loop
for (let i = 0; i < 5; i++) {
[Link](i); // 0, 1, 2, 3, 4
}
// Traverse array
const arr = ['a', 'b', 'c'];
for (let i = 0; i < [Link]; i++) {
[Link](arr[i]);
}
for...of (iterable: arrays, strings, maps)
const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
[Link](fruit);
}
// Works on strings too
for (const char of 'hello') {
[Link](char); // h, e, l, l, o
}
for...in (object keys)
const person = { name: 'Alice', age: 25, city: 'Delhi' };
for (const key in person) {
[Link](`${key}: ${person[key]}`);
}
// name: Alice / age: 25 / city: Delhi
while loop
let count = 0;
while (count < 5) {
[Link](count);
count++;
}
// do...while: always executes at least once
let x = 10;
do {
[Link](x); // Prints 10, even though condition is false
x++;
} while (x < 5);
break & continue
// break — exit loop immediately
for (let i = 0; i < 10; i++) {
if (i === 5) break;
[Link](i); // 0,1,2,3,4
}
// continue — skip current iteration
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) continue; // skip evens
[Link](i); // 1,3,5,7,9
}
💡 Infinite loops crash the browser/Node. Always ensure the loop condition will eventually become
false.
6. Functions
Functions are reusable blocks of code that perform a specific task. In JavaScript, functions are first-class
citizens — they can be stored in variables, passed as arguments, and returned from other functions.
6.1 Function Declaration
// Hoisted — can be called BEFORE the declaration in the file
function greet(name) {
return `Hello, ${name}!`;
}
[Link](greet('Alice')); // 'Hello, Alice!'
6.2 Function Expression
// NOT hoisted — must be declared before calling
const greet = function(name) {
return `Hello, ${name}!`;
};
[Link](greet('Bob'));
6.3 Arrow Functions (ES6)
// Full syntax
const add = (a, b) => { return a + b; };
// Implicit return (single expression, no braces)
const add = (a, b) => a + b;
// Single parameter — parentheses optional
const square = x => x * x;
// No parameters
const sayHi = () => [Link]('Hi!');
// Returning an object literal — wrap in parentheses
const makeUser = (name, age) => ({ name, age });
💡 Arrow functions do NOT have their own 'this'. They inherit 'this' from the surrounding scope
(lexical this). This makes them ideal for callbacks inside methods.
6.4 Parameters & Arguments
// Default parameters
function greet(name = 'Guest', greeting = 'Hello') {
[Link](`${greeting}, ${name}!`);
}
greet(); // 'Hello, Guest!'
greet('Alice'); // 'Hello, Alice!'
greet('Bob', 'Hi'); // 'Hi, Bob!'
// Rest parameters — collect remaining args into an array
function sum(first, ...rest) {
return first + [Link]((a, b) => a + b, 0);
}
[Link](sum(1, 2, 3, 4)); // 10
6.5 Scope
Scope Type Description
Global Variables declared outside any block/function. Accessible
everywhere.
Function Variables declared with var inside a function. Accessible within that
function only.
Block Variables declared with let/const inside {}. Accessible within that
block only.
Lexical A function can access variables from its outer (parent) scope.
const globalVar = 'I am global';
function outer() {
const outerVar = 'I am in outer';
function inner() {
const innerVar = 'I am in inner';
[Link](globalVar); // accessible
[Link](outerVar); // accessible (lexical scope)
[Link](innerVar); // accessible
}
// [Link](innerVar); // ReferenceError!
}
6.6 Closures
A closure is a function that retains access to its outer scope's variables, even after the outer function has
finished executing.
function makeCounter() {
let count = 0; // 'count' lives in the closure
return function() {
count++;
return count;
};
}
const counter = makeCounter();
[Link](counter()); // 1
[Link](counter()); // 2
[Link](counter()); // 3
// count is private — can't be accessed directly from outside
💡 Closures are used to create private variables, factory functions, and callbacks that remember
state.
7. Objects
Objects are collections of key-value pairs. Keys (also called properties) are strings (or Symbols), and values can
be any type — including functions (called methods).
7.1 Object Literals
const person = {
name: 'John',
age: 30,
isStudent: false,
greet() { // Method shorthand (ES6)
return `Hi, I'm ${[Link]}`;
}
};
// Access
[Link]([Link]); // 'John' — dot notation
[Link](person['age']); // 30 — bracket notation
const key = 'name';
[Link](person[key]); // 'John' — dynamic key
// Add / Update
[Link] = 'Delhi'; // add new property
[Link] = 31; // update existing
// Delete
delete [Link];
// Check if property exists
[Link]('name' in person); // true
7.2 this in Objects
Inside a regular function or method, 'this' refers to the object that called it. Arrow functions do NOT bind their
own 'this'.
const obj = {
name: 'Aniket',
// Regular function: this = obj
getName: function() { return [Link]; },
// Arrow function: this = outer (window/global), NOT obj
getNameArrow: () => [Link], // undefined in strict mode
// Practical: arrow preserves this in callbacks
getInfo: function() {
setTimeout(() => {
[Link]([Link]); // 'Aniket' — inherits from getInfo
}, 1000);
},
getInfoBad: function() {
setTimeout(function() {
[Link]([Link]); // undefined — this = window
}, 1000);
}
};
7.3 Iterating Over Objects
const person = { name: 'Alice', age: 25, city: 'Pune' };
// for...in — iterate over keys
for (const key in person) {
[Link](key, person[key]);
}
// [Link]() — array of keys
[Link](person).forEach(k => [Link](k));
// [Link]() — array of values
[Link](person).forEach(v => [Link](v));
// [Link]() — array of [key, value] pairs
[Link](person).forEach(([k, v]) => [Link](`${k}: ${v}`));
7.4 Nested Objects & Array of Objects
// Nested objects
const classInfo = {
aman: { grade: 'A+', city: 'Delhi' },
shraddha: { grade: 'A', city: 'Pune' },
};
[Link]([Link]); // 'A+'
// Array of objects (very common pattern)
const students = [
{ name: 'Aman', age: 20, city: 'Delhi' },
{ name: 'Shraddha', age: 22, city: 'Pune' },
{ name: 'Karan', age: 21, city: 'Kolkata' },
];
[Link](s => [Link] >= 21).map(s => [Link]); // ['Shraddha','Karan']
7.5 Math Object
[Link] // 3.141592653589793
[Link](16) // 4
[Link](2, 8) // 256 (same as 2**8)
[Link](-5) // 5
[Link](4.9) // 4 (round down)
[Link](4.1) // 5 (round up)
[Link](4.5) // 5 (nearest integer)
[Link](1,5,3) // 5
[Link](1,5,3) // 1
[Link]() // 0 ≤ x < 1 (random float)
// Random integer between min and max (inclusive)
const rand = (min, max) => [Link]([Link]() * (max - min + 1)) +
min;
rand(1, 6); // Simulate a dice roll
8. ES6+ Features
8.1 Spread Operator (...)
// Expand array elements
const nums = [1, 2, 3];
const more = [0, ...nums, 4, 5]; // [0,1,2,3,4,5]
// Pass array as individual arguments
function add(x, y, z) { return x + y + z; }
add(...nums); // 6
// Shallow copy of array
const copy = [...nums];
[Link](99); // nums unchanged
// Merge / copy objects
const a = { x: 1, y: 2 };
const b = { ...a, z: 3 }; // { x:1, y:2, z:3 }
const updated = { ...a, y: 99 }; // { x:1, y:99 } — override property
8.2 Rest Parameters (...)
// Collects remaining arguments into an array
function sum(first, second, ...rest) {
[Link](rest); // array of remaining args
return first + second + [Link]((a,b) => a+b, 0);
}
sum(1, 2, 3, 4, 5); // first=1, second=2, rest=[3,4,5]
8.3 Destructuring
Array Destructuring
const [a, b, c] = [1, 2, 3];
[Link](a, b, c); // 1 2 3
// Skip elements
const [first, , third] = [10, 20, 30]; // first=10, third=30
// Default values
const [x = 0, y = 0] = [5]; // x=5, y=0
// Swap variables
let m = 1, n = 2;
[m, n] = [n, m]; // m=2, n=1
Object Destructuring
const person = { name: 'Alice', age: 25, city: 'Pune' };
// Basic destructuring
const { name, age } = person;
// Rename variables
const { name: personName, age: personAge } = person;
// Default values
const { name: n, country = 'India' } = person; // country='India'
// In function parameters — very common pattern
function printUser({ name, age = 0 }) {
[Link](`${name} is ${age}`);
}
printUser(person);
8.4 Short-Circuit & Logical Assignment
// Logical OR assignment — assign if falsy
let x = null;
x ||= 'default'; // x = 'default'
// Logical AND assignment — assign only if truthy
let count = 5;
count &&= count + 1; // count = 6
// Nullish assignment — assign only if null/undefined
let val = 0;
val ??= 'fallback'; // val = 0 (0 is not null/undefined)
9. Higher-Order Functions
Higher-order functions (HOFs) are functions that take other functions as arguments, return functions, or both.
They enable functional programming patterns and cleaner code.
// Taking a function as argument
function multipleGreet(func, n) {
for (let i = 0; i < n; i++) func();
}
const greet = () => [Link]('Namaste');
multipleGreet(greet, 3); // Prints 'Namaste' 3 times
// Returning a function (factory pattern)
function createMultiplier(factor) {
return (num) => num * factor;
}
const double = createMultiplier(2);
const triple = createMultiplier(3);
[Link](double(5)); // 10
[Link](triple(5)); // 15
9.1 forEach, map, filter, reduce
const students = [
{ name: 'Alice', score: 85 },
{ name: 'Bob', score: 42 },
{ name: 'Carol', score: 91 },
{ name: 'Dave', score: 67 },
];
// forEach — side effects only
[Link](s => [Link]([Link]));
// map — transform each item
const names = [Link](s => [Link]);
// ['Alice', 'Bob', 'Carol', 'Dave']
// filter — keep matching items
const passed = [Link](s => [Link] >= 60);
// [Alice(85), Carol(91), Dave(67)]
// reduce — aggregate
const total = [Link]((sum, s) => sum + [Link], 0);
const avg = total / [Link]; // Average score
// Chaining — filter then map
const passedNames = students
.filter(s => [Link] >= 60)
.map(s => [Link]); // ['Alice', 'Carol', 'Dave']
💡 Chaining map/filter/reduce is extremely powerful. Read it left-to-right: filter the array, then
transform the result.
9.2 setTimeout & setInterval
// Execute ONCE after delay (milliseconds)
const timeoutId = setTimeout(() => {
[Link]('Runs after 2 seconds');
}, 2000);
clearTimeout(timeoutId); // Cancel before it fires
// Execute REPEATEDLY every interval
const intervalId = setInterval(() => {
[Link]('Runs every second');
}, 1000);
clearInterval(intervalId); // Stop repeating
10. Error Handling
JavaScript uses try/catch/finally blocks to gracefully handle runtime errors without crashing the program.
try {
// Code that might throw an error
const result = [Link]('{invalid json}');
} catch (error) {
// Runs if try block throws
[Link]('Caught:', [Link]);
[Link]('Stack:', [Link]);
} finally {
// ALWAYS runs, whether error occurred or not
[Link]('Cleanup done');
}
// Throw custom errors
function divide(a, b) {
if (b === 0) throw new Error('Division by zero!');
return a / b;
}
try {
divide(10, 0);
} catch (e) {
[Link]([Link]); // 'Division by zero!'
}
Error Type Cause
ReferenceError Using a variable that doesn't exist
TypeError Wrong type operation (e.g., [Link])
SyntaxError Invalid JS syntax (parse-time error)
RangeError Value out of allowed range (e.g., array -1 length)
URIError Malformed URI in decodeURI/encodeURI
11. DOM Manipulation
The Document Object Model (DOM) represents an HTML page as a tree of JavaScript objects. You can select,
create, modify, and remove elements using the DOM API.
11.1 Selecting Elements
// By ID — returns single element or null
const el = [Link]('myId');
// By class — returns live HTMLCollection
const items = [Link]('item');
// By tag — returns live HTMLCollection
const divs = [Link]('div');
// CSS selector — returns FIRST match
const first = [Link]('.item');
const btn = [Link]('#submit-btn');
// CSS selector — returns ALL matches as NodeList (static)
const all = [Link]('.item');
[Link](el => [Link](el)); // NodeList supports forEach
11.2 Reading & Modifying Content
const el = [Link]('#box');
// Content
[Link] = '<strong>Bold</strong>'; // Parses HTML
[Link] = 'Just text'; // Plain text only
[Link] = 'Visible text'; // Respects CSS visibility
// Attributes
[Link]('class'); // Get
[Link]('id', 'newId'); // Set
[Link]('style'); // Remove
// Inline styles (camelCase property names)
[Link] = 'red';
[Link] = '#fff';
[Link] = '18px';
11.3 classList
const el = [Link]('.card');
[Link]('active'); // Add a class
[Link]('hidden'); // Remove a class
[Link]('selected'); // Add if absent, remove if present
[Link]('active'); // Returns true/false
[Link]('old','new'); // Replace a class
💡 Prefer classList over setting [Link] = '...' directly — classList lets you add/remove
individual classes without losing others.
11.4 Creating & Removing Elements
// Create
const div = [Link]('div');
[Link] = 'Hello!';
[Link]('card');
// Insert
const parent = [Link]('container');
[Link](div); // Add at end
[Link](div); // Add at beginning
[Link]('Raw text'); // Can append text nodes too
// insertAdjacentElement positions
// 'beforebegin' — before the element
// 'afterbegin' — first child inside
// 'beforeend' — last child inside
// 'afterend' — after the element
[Link]('afterend', div);
// Remove
[Link](); // Modern, direct removal
11.5 Navigating the DOM Tree
const el = [Link]('#item');
[Link]; // Direct parent
[Link]; // HTMLCollection of child elements
[Link]; // First child element
[Link]; // Last child element
[Link]; // Previous sibling element
[Link]; // Next sibling element
12. DOM Events
Events are actions or occurrences (clicks, keypresses, form submissions) that the browser notifies you about
so you can respond with JavaScript.
12.1 addEventListener
const btn = [Link]('button');
// Method 1: addEventListener (PREFERRED — can add multiple listeners)
[Link]('click', function(event) {
[Link]('Clicked!');
[Link]([Link]); // The element that was clicked
});
// Method 2: Event handler property (only one handler at a time)
[Link] = () => [Link]('Clicked via onclick');
// Remove a listener (must reference the same function)
function handleClick() { [Link]('click'); }
[Link]('click', handleClick);
[Link]('click', handleClick);
12.2 Common Events
Event When it fires
click Mouse button clicked
dblclick Double click
mouseover / mouseout Mouse enters / leaves element
mousedown / mouseup Mouse button pressed / released
mousemove Mouse moves over element
keydown / keyup Key pressed / released
Event When it fires
keypress Key pressed (deprecated — use keydown)
submit Form submitted
input Input value changes (fires on every keystroke)
change Input loses focus after value changed
focus / blur Element gains / loses focus
load Page or image fully loaded
DOMContentLoaded HTML parsed (before images/CSS)
scroll Page or element scrolled
12.3 The Event Object
[Link]('keydown', function(event) {
[Link]([Link]); // 'Enter', 'a', 'ArrowUp', etc.
[Link]([Link]); // 'KeyA', 'Enter', 'ArrowUp'
[Link]([Link]); // true if Ctrl held
if ([Link] === 'Enter') { /* handle enter */ }
});
// Form submit — prevent default page reload
const form = [Link]('form');
[Link]('submit', function(event) {
[Link]();
const username = [Link]('#user').value;
[Link]('Submitted:', username);
});
12.4 Event Bubbling & Delegation
Event Bubbling: Events propagate UP from the target element to the document root, triggering handlers at
each level.
Event Delegation: Instead of attaching listeners to every child, attach ONE listener to the parent and check
[Link].
// Without delegation — inefficient for many items
[Link]('.item').forEach(item => {
[Link]('click', handleClick);
});
// WITH delegation — one listener on parent
[Link]('#list').addEventListener('click', function(e) {
if ([Link]('item')) {
[Link]('Item clicked:', [Link]);
}
});
// Works even for dynamically added items!
// Stop bubbling
[Link]('click', e => [Link]());
13. JavaScript Engine & Event Loop
JavaScript is single-threaded — it can only do one thing at a time. The event loop is the mechanism that
enables non-blocking asynchronous behavior despite this constraint.
13.1 How Code Executes
• When a JS file loads, a Global Execution Context is created.
• Code is compiled and executed line by line.
• Each function call creates a new Execution Context pushed onto the Call Stack.
• When the function finishes, its context is popped off the stack.
• The Call Stack follows LIFO (Last In, First Out).
function a() { b(); }
function b() { c(); }
function c() { [Link]('deep'); }
a();
// Call stack at deepest point:
// [c] ← top
// [b]
// [a]
// [global]
13.2 The Event Loop
Asynchronous operations (setTimeout, fetch, DOM events) are handled by Web APIs. When complete, their
callbacks are queued and the event loop schedules them.
• 1. Async operation starts → handed off to Web API (not the JS engine).
• 2. JS engine continues executing remaining synchronous code.
• 3. When async operation finishes, its callback enters the Callback Queue (macrotask queue).
• 4. When the Call Stack is empty, the Event Loop picks the next callback and runs it.
• 5. Promise callbacks go to the Microtask Queue, which is processed BEFORE the callback queue.
[Link]('1 — start');
setTimeout(() => [Link]('3 — timeout'), 0);
[Link]().then(() => [Link]('2 — promise'));
[Link]('4 — end');
// Output order: 1, 4, 2, 3
// Synchronous first, then microtasks (promise), then macrotasks (timeout)
💡 Microtasks (Promises) always run before macrotasks (setTimeout, setInterval) — even if the
timeout is 0ms.
14. Asynchronous JavaScript
14.1 Callback Hell
Before Promises, async operations were handled via callbacks. Nesting multiple async operations led to
deeply indented, hard-to-read code:
getData(function(data) {
processData(data, function(processed) {
saveData(processed, function(saved) {
sendEmail(saved, function(result) {
// 4 levels deep — 'callback hell' / 'pyramid of doom'
});
});
});
});
14.2 Promises
A Promise is an object representing the eventual completion or failure of an async operation. It can be in
three states: pending, fulfilled, or rejected.
const myPromise = new Promise((resolve, reject) => {
// Executor runs synchronously
setTimeout(() => {
const success = true;
if (success) {
resolve('Operation completed!'); // → fulfilled
} else {
reject('Something went wrong.'); // → rejected
}
}, 1000);
});
myPromise
.then(result => [Link](result)) // runs on resolve
.catch(error => [Link](error)) // runs on reject
.finally(() => [Link]('Done')); // always runs
// Promise chaining
fetch('/api/user')
.then(res => [Link]())
.then(user => fetchPosts([Link]))
.then(posts => [Link](posts))
.catch(err => [Link]('Error:', err));
// One catch handles errors from ANY step in the chain
14.3 async / await
async/await is syntactic sugar over Promises that makes async code look and behave like synchronous code —
much easier to read.
// async function always returns a Promise
async function fetchUser() {
try {
const response = await fetch('[Link]
// 'await' pauses HERE until the fetch resolves
if (![Link]) throw new Error(`HTTP error: ${[Link]}`);
const user = await [Link]();
return user; // Promise resolves with this value
} catch (error) {
[Link]('Fetch failed:', error);
throw error; // Re-throw so caller can handle
}
}
// Calling an async function
fetchUser()
.then(user => [Link](user))
.catch(err => [Link](err));
// Or from within another async function:
async function main() {
const user = await fetchUser();
[Link](user);
}
main();
💡 await can only be used inside an async function. The function pauses at each await but the rest
of the JS engine continues running — it does NOT block the browser.
14.4 [Link] & [Link]
// [Link] — runs in parallel, resolves when ALL resolve
// Rejects immediately if ANY promise rejects
const [user, posts, comments] = await [Link]([
fetch('/api/user').then(r => [Link]()),
fetch('/api/posts').then(r => [Link]()),
fetch('/api/comments').then(r => [Link]()),
]);
// [Link] — resolves when ALL settle (even if some reject)
const results = await [Link]([p1, p2, p3]);
[Link](r => {
if ([Link] === 'fulfilled') [Link]([Link]);
else [Link]('Failed:', [Link]);
});
15. APIs, JSON & Fetch
15.1 What is an API?
API (Application Programming Interface) is like a waiter in a restaurant: you (client) make a request, the
waiter (API) takes it to the kitchen (server), and brings back the response. Web APIs use HTTP/HTTPS and
typically exchange data in JSON format.
HTTP Verb Purpose
GET Retrieve data (read-only, no body)
POST Send data to create a new resource
PUT Replace an entire resource with new data
PATCH Update part of a resource
DELETE Remove a resource
HTTP Status Code Groups
Code Range Meaning
1xx — Informational Request received, processing continues (100 Continue)
2xx — Success 200 OK, 201 Created, 204 No Content
3xx — Redirection 301 Moved Permanently, 302 Found
4xx — Client Error 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found
5xx — Server Error 500 Internal Server Error, 502 Bad Gateway, 503 Unavailable
15.2 JSON
JSON (JavaScript Object Notation) is a lightweight text format for data exchange. It looks like JS object literals
but with stricter rules.
JSON Rule Detail
Keys must be strings Keys must be in double quotes: {"name": "Alice"}
Permitted value types String, Number, Boolean, null, Array, Object
NOT permitted Functions, undefined, Symbol, trailing commas
JSON Rule Detail
[Link]() Convert JSON string → JS object
[Link]() Convert JS object → JSON string
// JSON string (from server / file)
const jsonStr = '{"name":"Alice","age":25,"hobbies":["reading"]}';
// Parse: JSON string → JS object
const obj = [Link](jsonStr);
[Link]([Link]); // 'Alice'
// Stringify: JS object → JSON string
const backToString = [Link](obj, null, 2); // 2-space indent
[Link](backToString);
15.3 Fetch API
// Basic GET request
async function getUsers() {
try {
const response = await
fetch('[Link]
if (![Link]) {
throw new Error(`HTTP error! status: ${[Link]}`);
}
const users = await [Link](); // Parse JSON body
[Link](users);
} catch (error) {
[Link]('Error:', error);
}
}
// POST request
async function createUser(userData) {
const response = await fetch('[Link] {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your-token-here',
},
body: [Link](userData),
});
const newUser = await [Link]();
return newUser;
}
15.4 URL Structure
// Full URL anatomy:
// [Link]
// protocol hostname path path-param query string
// Query parameters (after ?)
// Key-value pairs: param=value, separated by &
// [Link]
// Path parameters (in URL path) — identify a specific resource
// [Link] → /users/42
16. Object-Oriented Programming (OOP)
OOP is a programming paradigm that models real-world entities as objects containing data (properties) and
behavior (methods). JS supports OOP through prototypes and the ES6 class syntax.
16.1 Why OOP?
Imagine you need data for 1000 students. Creating a separate object literal for each one is impractical. OOP
solves this by creating a CLASS — a blueprint that defines the structure — and then instantiating as many
OBJECTS from it as needed.
16.2 Prototypes
Every JavaScript object has a hidden internal [[Prototype]] property linking it to another object. This chain of
links — the prototype chain — enables inheritance.
const arr = [1, 2, 3];
// arr's prototype chain:
// arr → [Link] → [Link] → null
// push/pop/map all live on [Link]
// Every array SHARES these methods — not individual copies
// Access prototype
[Link](arr); // [Link] (preferred)
arr.__proto__; // Same, but deprecated
// Check prototype
[Link](arr); // true
💡 All instances share prototype methods — they don't get their own copy. This saves memory
significantly compared to factory functions that embed methods in each object.
16.3 Constructor Functions (Pre-ES6)
function Student(name, age) {
[Link] = name; // Instance properties
[Link] = age;
}
// Adding methods to the PROTOTYPE (shared by all instances)
[Link] = function() {
return `${[Link]} is ${[Link]} years old.`;
};
// 'new' keyword does 4 things:
// 1. Creates a new empty object {}
// 2. Sets its prototype to [Link]
// 3. Calls Student() with 'this' = the new object
// 4. Returns the new object
const s1 = new Student('Alice', 20);
const s2 = new Student('Bob', 22);
[Link]([Link]()); // 'Alice is 20 years old.'
// s1 and s2 share the SAME getDetails function via prototype
16.4 ES6 Classes
The class keyword provides a cleaner, more readable syntax for creating constructor functions and prototype-
based inheritance. Internally, it is syntactic sugar over prototypes.
class Person {
// constructor: runs when 'new Person()' is called
constructor(name, age) {
[Link] = name; // Instance property
[Link] = age;
}
// Methods defined here go on [Link] (shared)
greet() {
[Link](`Hi, I'm ${[Link]}`);
}
// Getter
get info() {
return `${[Link]}, age ${[Link]}`;
}
// Static method — called on the class, not instances
static create(name, age) {
return new Person(name, age);
}
}
const p = new Person('Alice', 25);
[Link](); // 'Hi, I'm Alice'
[Link]([Link]); // 'Alice, age 25'
const p2 = [Link]('Bob', 30); // static method
16.5 Inheritance with extends & super
The extends keyword creates a class that inherits from another. The super keyword calls the parent class's
constructor or methods.
class Person {
constructor(name, age) {
[Link] = name;
[Link] = age;
}
greet() { [Link](`Hi, I'm ${[Link]}`); }
toString() { return `${[Link]} (age ${[Link]})`; }
}
class Student extends Person {
constructor(name, age, rollNo) {
super(name, age); // MUST call super before using 'this'
[Link] = rollNo;
}
study() { [Link](`${[Link]} is studying.`); }
// Override parent method
greet() {
[Link](); // Call parent's greet
[Link](`I'm roll no. ${[Link]}`);
}
}
class Teacher extends Person {
constructor(name, age, subject) {
super(name, age);
[Link] = subject;
}
teach() { [Link](`${[Link]} teaches ${[Link]}`); }
}
const stu = new Student('Ayush', 19, 'CS101');
[Link](); // Calls overridden [Link]
[Link]();
const tch = new Teacher('Aniket', 30, 'JavaScript');
[Link]();
[Link](); // Inherited from Person
// instanceof checks
[Link](stu instanceof Student); // true
[Link](stu instanceof Person); // true (inheritance chain)
16.6 Private Fields (ES2022)
Fields prefixed with # are truly private — they cannot be accessed from outside the class.
class BankAccount {
#balance = 0; // Private field
constructor(owner, initialBalance) {
[Link] = owner;
this.#balance = initialBalance;
}
deposit(amount) {
if (amount > 0) this.#balance += amount;
}
get balance() { return this.#balance; } // Read-only getter
}
const acc = new BankAccount('Alice', 1000);
[Link](500);
[Link]([Link]); // 1500
// [Link](acc.#balance); // SyntaxError — private!
16.7 Four Pillars of OOP
Pillar In JavaScript
Encapsulation Bundle data and methods together. Use # private fields or closures
to hide internal state.
Inheritance Use extends to inherit from a parent class. Reuse and extend
behavior.
Polymorphism Override parent methods in child classes. Same method name,
different behavior.
Abstraction Expose only what's necessary. Hide complex implementation details.
17. Quick Reference Cheat Sheet
Variable Declarations
let x = 1; // block-scoped, reassignable
const y = 2; // block-scoped, not reassignable
var z = 3; // function-scoped, avoid
Arrow Functions
const fn = (a, b) => a + b; // implicit return
const fn2 = (a, b) => { return a + b; }; // explicit
const fn3 = x => x * 2; // single param, no parens needed
const fn4 = () => ({key: 'val'}); // return object literal
Destructuring
const [a, b] = [1, 2]; // array
const { name, age: personAge = 0 } = user; // object with rename +
default
Spread & Rest
const arr = [...oldArr, newItem]; // spread: expand
const obj = { ...oldObj, key: 'val' }; // spread: merge/override
function f(first, ...rest) { /* rest is array */ } // rest: collect
Promises & async/await
const p = new Promise((res, rej) => { /* ... */ });
[Link](v => {}).catch(e => {}).finally(() => {});
async function f() {
try {
const data = await fetch('/api').then(r => [Link]());
} catch(e) { /* handle */ }
}
Classes
class Animal {
#sound;
constructor(name, sound) { [Link] = name; this.#sound = sound; }
speak() { return `${[Link]} says ${this.#sound}`; }
static kingdom() { return 'Animalia'; }
}
class Dog extends Animal {
constructor(name) { super(name, 'Woof'); }
fetch() { return `${[Link]} fetches the ball!`; }
}
const d = new Dog('Rex');
[Link]([Link]()); // 'Rex says Woof'
[Link]([Link]()); // 'Rex fetches the ball!'
Array Methods Summary
Method Returns Mutates?
push / pop new length / removed item Yes
shift / unshift removed item / new length Yes
splice(start,n) removed items Yes
sort / reverse array (same ref) Yes
map(fn) new transformed array No
filter(fn) new filtered array No
Method Returns Mutates?
reduce(fn, init) single accumulated value No
find(fn) first matching element No
some / every boolean No
slice(start,end) new sub-array No
concat / spread new combined array No
flat / flatMap new flattened array No
— End of JavaScript Notes —