JavaScript Notes
HubYour First JavaScript Program — Hello World & Beyond Complete Guide 2026History of JavaScript — Complete Timeline from 1995 to 2026How JavaScript Runs — Complete Guide to Execution, Call Stack & Event LoopJavaScript Engine Explained — V8, JIT Compilation & How Code Gets FastJavaScript Use Cases — 15 Things You Can Build with JavaScript (2026)JavaScript vs Other Languages — Complete Comparison Guide 2026What is JavaScript? Complete BeginnerWhy Learn JavaScript in 2026? Career, Salary, Scope & Benefits GuideJavaScript Break Statement Tutorial – Complete Guide with ExamplesJavaScript Break and Continue Statements – Complete Guide with ExamplesJavaScript Continue Statement Tutorial – Skip Iterations with ExamplesJavaScript Do While Loop Tutorial – Execute at Least Once with ExamplesJavaScript Do-While Loop Tutorial – Complete Guide with ExamplesJavaScript For Loop Tutorial – Complete Guide with ExamplesJavaScript If Statement Tutorial – Conditional Logic with ExamplesJavaScript If Else Statement Tutorial – Complete Guide with ExamplesJavaScript If Statement Tutorial – Complete Guide with ExamplesJavaScript Nested If Statement Tutorial – Multi-Level Conditions with ExamplesNested Loops in JavaScriptJavaScript Control Flow Practice Programs – 20+ Exercises with SolutionsJavaScript Switch Statement Tutorial – Case Matching with ExamplesSwitch Statement in JavaScriptJavaScript While Loop Tutorial – Complete Guide with ExamplesJavaScript Arrow Functions Tutorial – Syntax, Use Cases & this BindingJavaScript Callback Functions Explained – Synchronous & AsynchronousJavaScript Closures Explained – Lexical Scope, Private State & MemoryJavaScript Function Declaration Tutorial – Hoisting, Syntax & ScopeJavaScript Function Expression Tutorial – Anonymous, Named & AssignedJavaScript Higher Order Functions Tutorial – map, filter, reduce & Custom HOFsJavaScript IIFE Explained – Immediately Invoked Function ExpressionJavaScript Functions Practice Programs – 20+ Exercises with SolutionsJavaScript Recursion Tutorial – Call Stack, Base Case & Recursive PatternsJavaScript Array Basics - Complete BeginnerJavaScript Array Methods - Complete Reference Guide with ExamplesJavaScript Array Programs - 20+ Practice Problems with SolutionsJavaScript Arrays Basics - Complete Guide with Examples & DiagramsJavaScript Array filter() Method - Complete Tutorial with ExamplesJavaScript filter() Method — Complete Guide with Examples 2026JavaScript Array find() Method - Complete Tutorial with ExamplesJavaScript find() & findIndex() — Complete Guide 2026JavaScript Array map() Method - Complete Tutorial with ExamplesJavaScript map() Method — Transform Arrays Complete Guide 2026JavaScript map() vs forEach() - Key Differences with ExamplesJavaScript Array push() and pop() - Complete Tutorial with ExamplesJavaScript Array reduce() Method - Complete Tutorial with ExamplesJavaScript reduce() Method — Complete Deep Dive with Examples 2026JavaScript Array shift() and unshift() - Complete Tutorial with ExamplesJavaScript Array sort() Method - Complete Tutorial with ExamplesJavaScript splice() vs slice() - Complete Tutorial with ExamplesJavaScript Object Destructuring - Complete Guide with ExamplesJavaScript Objects - Complete Guide to Object Basics with ExamplesJavaScript Object Methods - Built-in Methods & Custom Methods Complete GuideJavaScript Object Programs - Practice Problems with SolutionsJavaScript Object Properties - Keys, Values, Descriptors & Dynamic PropertiesJavaScript Rest Operator (...) - Parameters, Destructuring & Complete GuideJavaScript Spread Operator (...) - Complete Guide with ExamplesJavaScript this Keyword - Complete Guide with Binding Rules & ExamplesJavaScript String Basics - Complete Guide to Strings with ExamplesJavaScript String Methods - Complete Reference with Examples & OutputJavaScript String Programs - Practice Problems with SolutionsJavaScript String Replacing - replace(), replaceAll() & Regex Patterns GuideJavaScript String Searching Methods - includes, indexOf, startsWith, match GuideJavaScript Template Literals (ES6) - Complete Guide with Tagged TemplatesJavaScript DOM Changing Content - textContent, innerHTML, setAttribute Complete GuideJavaScript DOM Changing Styles - CSS Manipulation, classList & getComputedStyleJavaScript DOM Creating Elements - createElement, appendChild, DocumentFragment GuideJavaScript DOM Introduction - Complete Guide to Document Object ModelJavaScript DOM Traversal - Navigate Parent, Child & Sibling NodesJavaScript DOM Forms - Form Handling, Validation & FormData Complete GuideJavaScript localStorage - Complete Guide to Web Storage APIlocalStorage vs sessionStorage - JavaScript Web Storage Comparison GuideJavaScript DOM Removing Elements - remove(), removeChild() Complete GuideJavaScript DOM Selecting Elements - querySelector, getElementById Complete GuideJavaScript sessionStorage - Complete Guide to Session-Based Web StorageJavaScript Click Event - addEventListener, Event Handler Complete GuideEvent Bubbling in JavaScript – Complete Guide with Examples (2026)Event Capturing in JavaScript – Complete Guide to Capture Phase (2026)Event Delegation in JavaScript – Complete Guide with Examples (2026)JavaScript Event Object – Complete Guide with Examples (2026)JavaScript Form Events – Complete Guide with Examples (2026)JavaScript Keyboard Events – Complete Guide to keydown, keyup & Key Properties (2026)JavaScript Mouse Events – Complete Guide with Examples (2026)JavaScript Async Await - Complete Guide with Examples & Error HandlingJavaScript Call Stack - Complete Guide with Visual Diagrams & ExamplesJavaScript Callback Queue (Task Queue) - Complete Guide with DiagramsJavaScript Callbacks - Complete Guide with Callback Hell & PatternsJavaScript Event Loop - Complete Guide with Visual Diagrams & ExamplesJavaScript Fetch API - Complete Guide with Examples, Error Handling & Async/AwaitJSON in JavaScript - Complete Guide: Parse, Stringify, Fetch & Error HandlingJavaScript Promise.all, Promise.race, Promise.any, Promise.allSettled — Complete Guide 2026JavaScript Promises - Complete Guide with Chaining, Error Handling & Event LoopSynchronous vs Asynchronous JavaScript — Complete Explanation 2026JavaScript Web APIs - Complete Guide: setTimeout, fetch, DOM Events & MoreClosures in JavaScript — Complete Guide with Examples 2026Hoisting in JavaScript — Complete Guide with Examples 2026Prototype in JavaScript — Complete Guide with Examples 2026Scope in JavaScript — Complete Guide with Examples 2026Browser Object Model (BOM) in JavaScript — Complete GuideCanvas API in JavaScript — Complete Drawing & Animation GuideDrag and Drop API in JavaScript — Complete TutorialGeolocation API in JavaScript — Get User Location TutorialHistory API in JavaScript — SPA Routing & pushState GuideNotification API in JavaScript — Push Notifications TutorialService Workers in JavaScript — Offline, Caching & PWA GuideWeb Storage API in JavaScript — localStorage & sessionStorage GuideWeb Workers in JavaScript — Multithreading & Background Tasks GuideJavaScript Interview — Behavioral Questions and Soft Skills Guide 2026Common JavaScript Interview Mistakes — What to Avoid 2026JavaScript Interview Tips — Strategy and Preparation Guide 2026JavaScript Mock Interview — Practice Questions with Solutions 2026JavaScript System Design — Frontend Architecture Interview Guide 2026JavaScript apply() Method - Complete Guide with ExamplesJavaScript bind() Method - Complete Guide with ExamplesJavaScript call() Method - Complete Guide with ExamplesJavaScript call() vs apply() vs bind() - Complete Comparison GuideJavaScript Currying - Complete Guide with ExamplesJavaScript Debounce - Complete Guide with Timeline DiagramsJavaScript Execution Context - Complete Guide with Stack DiagramsJavaScript Garbage Collection - Memory Lifecycle & Mark-and-Sweep GuideJavaScript Generators - Complete Guide with yield and IterationJavaScript Hoisting - Complete Guide with var, let, const & FunctionsJavaScript Iterators - Complete Guide with Iterator ProtocolJavaScript Lexical Scope - Complete Guide with Scope Chain DiagramsJavaScript Memory Management - Complete Guide with Lifecycle DiagramsJavaScript Modules - Complete Guide with import export ExamplesJavaScript Scope - Complete Guide with var, let, const & Scope ChainJavaScript Symbols - Complete Guide with Well-Known SymbolsJavaScript Throttle - Complete Guide with Timeline DiagramsJavaScript Comments Complete Guide – Single Line, Multi-line & JSDoc with ExamplesJavaScript Data Types Complete Guide – Primitives, Objects & typeof with ExamplesJavaScript Input and Output Complete Guide – console.log, prompt, alert & DOM with ExamplesJavaScript Keywords Complete Guide – Reserved Words List with Examples for BeginnersJavaScript null vs undefined – Complete Guide with Differences, Examples & Interview Q&AJavaScript Operators Complete Guide – Arithmetic, Comparison, Logical & More with ExamplesJavaScript Strict Mode Complete Guide – JavaScript Type Conversion Complete Guide – Explicit & Implicit Coercion with ExamplesJavaScript var vs let vs const – Complete Guide with Scope, Hoisting & Best PracticesJavaScript Variables Complete Guide – Declaration, Naming Rules & Memory Model for BeginnersDeque (Double-Ended Queue) in JavaScript — Complete GuideLinked List in JavaScript — Nodes, Pointers & Operations GuideJavaScript Map — Key-Value Data Structure Complete GuideJavaScript Numbers — IEEE 754, Precision, and Number Methods GuidePriority Queue in JavaScript — Min Heap Implementation GuideQueue Data Structure in JavaScript — FIFO, Enqueue & Dequeue ExplainedJavaScript Set — Unique Values Data Structure GuideSorting Algorithms in JavaScript — Bubble, Merge, Quick Sort GuideStack Data Structure in JavaScript — LIFO, Push, Pop ExplainedJavaScript Typed Arrays — ArrayBuffer, Int32Array, Float64Array GuideJavaScript WeakMap — Weak References, Memory Management GuideJavaScript WeakSet — Complete Guide with Examples 2026Applications of JavaScript — Where JS is Used in 2026 Complete GuideJavaScript Backend Frameworks — Node.js, Express, NestJS Complete Guide 2026JavaScript Frontend Libraries — React, Vue, Angular, Svelte Complete Overview 2026JavaScript Full-Stack Frameworks — Next.js, Remix, Astro Complete Guide 2026JavaScript Career Paths & Jobs — Salary, Roles & Roadmap 2026JavaScript Libraries vs Frameworks — Difference & Examples Complete Guide 2026JavaScript Custom Errors – Extend Error Class, Custom Error Types & instanceofJavaScript Debugging – console Methods, DevTools, Breakpoints & Error Stack TracesJavaScript throw Statement – Throw Errors, Custom Messages & Error TypesJavaScript Try Catch Finally – Error Handling Complete GuideTop 30 JavaScript Closure Interview Questions & Answers 2026Top 30 JavaScript Coding Interview Questions 2026 (With Solutions)Top 25 JavaScript Event Loop Interview Questions & Answers 2026Top 50 JavaScript Interview Questions & Answers 2026Top 30 JavaScript Promise Interview Questions & Answers 202650 Tricky JavaScript Output Questions 2026 (With Answers)Build a JavaScript Calculator - Step by Step Project TutorialBuild a JavaScript Image Carousel - Step by Step Project TutorialBuild a JavaScript Counter Application - Step by Step Project TutorialBuild a JavaScript Digital Clock - Step by Step Project TutorialBuild a Dynamic Resume Builder in JavaScript - Step by Step TutorialBuild a JavaScript Email Validator - Step by Step Project TutorialBuild a JavaScript Employee Database Management App - Step by Step TutorialBuild a JavaScript Expense Tracker - Step by Step Project TutorialBuild a GitHub Profile Search App in JavaScript - Step by Step TutorialBuild a JavaScript Image Slider - Step by Step Project TutorialBuild a JavaScript Multi-Step Progress Bar - Step by Step TutorialBuild JavaScript Nested Chat Comments - Step by Step Project TutorialBuild a JavaScript Notes App - Step by Step Project TutorialBuild a JavaScript OTP Input Field - Step by Step Project TutorialBuild a JavaScript Palindrome Checker - Step by Step Project TutorialBuild a JavaScript Price Range Slider - Step by Step Project TutorialBuild a JavaScript Prime Number Checker - Step by Step Project TutorialBuild a JavaScript QR Code Generator - Step by Step Project TutorialBuild a JavaScript QR Code Scanner - Step by Step Project TutorialBuild a JavaScript Quiz App - Step by Step Project TutorialBuild a JavaScript Random Number Generator - Step by Step TutorialBuild a JavaScript Random Password Generator - Step by Step TutorialJavaScript Image Resize & Compress — Canvas API Project 2026JavaScript Responsive Admin Dashboard — DOM & CSS Project 2026JavaScript Show/Hide Password Toggle — Beginner DOM Project 2026JavaScript Sortable Filterable Table — DOM & Array Methods Project 2026JavaScript Stopwatch Project — setInterval & DOM Tutorial 2026JavaScript Student Grade Calculator — Arrays & Logic Project 2026JavaScript Task Scheduler Project — CRUD & localStorage Tutorial 2026JavaScript Tic-Tac-Toe Game — DOM Manipulation Project Tutorial 2026JavaScript Toast Notification Project — Custom Alerts Tutorial 2026Build a Todo App in JavaScript - Step by Step Project TutorialJavaScript Unicode Character Value Finder — charCodeAt & fromCharCode Project 2026JavaScript Weather App Project — Fetch API & DOM Complete Tutorial 2026JavaScript Cheat Sheet 2026 — Complete Quick ReferenceImportant JavaScript Concepts Every Developer Must Know in 2026JavaScript One Shot Notes 2026 — Complete JS in One PageJavaScript Quick Revision Notes — Interview Prep in 30 Minutes 2026Abstraction in JavaScript OOP – Hide Complexity, Expose SimplicityJavaScript Classes Tutorial – ES6 Class Syntax, Inheritance & MoreJavaScript Constructor Functions – new Keyword, Prototype & OOP PatternsEncapsulation in JavaScript – Private Fields, Getters, Setters & Data ProtectionJavaScript Inheritance – extends, super, and Prototype-Based InheritanceObject-Oriented Programming in JavaScript – OOP Concepts Complete GuideJavaScript OOP Projects – Build Real-World Apps with Classes & OOPPolymorphism in JavaScript – Method Overriding, Duck Typing & Many FormsJavaScript Prototype Chain – How Property Lookup Works in JavaScriptJavaScript Prototypes – Prototype-Based Inheritance, Object.create & prototype PropertyJavaScript Advanced Practice Problems — 15+ Interview-Level Challenges 2026JavaScript Assignments — 10 Project-Based Learning Tasks 2026JavaScript Beginner Practice Problems — 20+ Coding Exercises 2026JavaScript Coding Challenges — 25 Interview-Style Problems 2026JavaScript Intermediate Practice Problems — 20+ Coding Challenges 2026JavaScript MCQs — 50 Multiple Choice Questions with Answers 2026JavaScript Regex Character Classes – [abc], [^abc], Ranges & ShortcutsJavaScript Regex Email Validation – Pattern, Edge Cases & Best PracticesJavaScript Regex Flags – g, i, m, s, u, y Flags Explained with ExamplesJavaScript Regex Groups – Capturing, Non-Capturing & Named GroupsJavaScript Number Validation with Regex — Complete Patterns & Examples 2026JavaScript Password Validation with Regex — Strength Checker & Patterns 2026JavaScript Regex Quantifiers – *, +, ?, {n,m}, Greedy vs Lazy MatchingJavaScript Regex Basics – Regular Expressions Tutorial for BeginnersJavaScript Regex Projects — 10 Practical Mini-Projects with Code 2026JavaScript URL Validation with Regex — Complete Patterns & Examples 2026JavaScript Username Validation with Regex — Patterns & Form Examples 2026JavaScript TutorialJavaScript Lazy Loading — Images, Modules & Components Complete Guide 2026JavaScript Performance Optimization — Speed Up Your Code Complete Guide 2026JavaScript Unit Testing with Jest — Complete Guide for Beginners 2026
Complete JavaScript in one page. One-shot notes covering every JavaScript topic from basics to advanced — variables, functions, OOP, async, DOM, ES6+ for 2026 interviews.
Everything you need to know about JavaScript, organized for maximum retention. Read this once and you'll have a solid mental model of the entire language.
Part 2: Variables & Types
Declaration Keywords
js example
var x = 1; // function-scoped, hoisted as undefined, legacy
let y = 2; // block-scoped, TDZ, modern standard
const z = 3; // block-scoped, TDZ, immutable bindingAll 8 Data Types
js example
// 7 Primitives (stored by value)
number: 42, 3.14, NaN, Infinity, -Infinity
string: "hello", 'world', `template`
boolean: true, false
undefined: declared but not assigned
null: intentionally empty value
symbol: Symbol("unique")
bigint: 9007199254740993n
// 1 Object type (stored by reference)
object: {}, [], function(){}, /regex/, new Date()Checking Types
js example
typeof 42 // "number"
typeof null // "object" ← BUG
Array.isArray([]) // true
x instanceof Array // truePart 3: Operators & Coercion
Equality
js example
1 == "1" // true (type coercion — avoid)
1 === "1" // false (strict — always use this)
null == undefined // true (special case)
NaN === NaN // false (use Number.isNaN instead)Logical Operators
Example
// Short-circuit: returns value, not just true/false
"a" || "b" // "a" (first truthy)
"" || "b" // "b" (fallback)
"a" && "b" // "b" (last if all truthy)
null && fn() // null (fn not called)
// Nullish coalescing (only null/undefined triggers fallback)
null ?? "default" // "default"
0 ?? "default" // 0 (!! difference from ||)
"" ?? "default" // "" (!! difference from ||)
// Optional chaining
user?.address?.city // undefined if any link is null/undefined
arr?.[0] // safe array access
fn?.() // safe function call
Part 4: Functions — Everything
Example
// 1. Function Declaration — hoisted
function add(a, b) { return a + b; }
// 2. Function Expression — not hoisted
const multiply = function(a, b) { return a * b; };
// 3. Arrow Function — concise, lexical 'this'
const square = n => n * n;
const greet = (name, greeting = "Hello") => `${greeting}, ${name}!`;
// 4. IIFE — Immediately Invoked
(function() { /* runs once */ })();
(() => { /* arrow IIFE */ })();
// 5. Generator — can pause/resume
function* gen() { yield 1; yield 2; yield 3; }
const g = gen();
g.next(); // { value: 1, done: false }
// 6. Async Function — returns Promise
async function fetchData() {
const data = await fetch("/api");
return data.json();
}
Function Parameters
js example
// Default
function greet(name = "World") {}
// Rest (must be last)
function sum(first, ...rest) {}
// Destructured
function user({ name, age = 25 }) {}
// Arguments object (not in arrow functions)
function fn() { console.log(arguments); }Part 5: Scope & Closures
Scope Types
text example
1. Global Scope → accessible everywhere
2. Function Scope → var lives within function
3. Block Scope → let/const within {}
4. Module Scope → top-level stays in moduleClosure (The King of JS Concepts)
js example
// Closure = function + its lexical environment
function bank(initial) {
let balance = initial; // PRIVATE
return {
deposit(n) { balance += n; return balance; },
withdraw(n) { balance = Math.max(0, balance - n); return balance; },
check() { return balance; }
};
}
const account = bank(100);
account.deposit(50); // 150
account.withdraw(30); // 120
account.check(); // 120
// account.balance → undefined (private!)Classic Loop Trap
Example
// ❌ var — all share same i
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // 3, 3, 3
}
// ✅ let — new binding per iteration
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100); // 0, 1, 2
}
Part 6: this & Prototypes
this Rules
text example
1. Default: standalone fn → window (non-strict) / undefined (strict)
2. Method: obj.fn() → obj
3. new: new Fn() → new instance
4. Explicit: .call(ctx), .apply(ctx), .bind(ctx) → ctx
5. Arrow: inherits from lexical scopePrototype Chain
text example
instance
→ Constructor.prototype (shared methods)
→ Object.prototype (toString, hasOwnProperty...)
→ nulljs example
// Constructor pattern
function Animal(name) { this.name = name; } // own property
Animal.prototype.speak = function() { return this.name; }; // shared
// Modern ES6 class
class Animal {
constructor(name) { this.name = name; }
speak() { return this.name; }
}
class Dog extends Animal {
constructor(name) { super(name); }
bark() { return "Woof!"; }
}Part 7: Arrays — Essential Methods
Mutating
text example
push(x) — add to end
pop() — remove from end
unshift(x) — add to start
shift() — remove from start
splice(i,n,x) — remove/insert at index
sort(fn) — sort in-place
reverse() — reverse in-place
fill(x,s,e) — fill with valueNon-Mutating
text example
slice(s,e) — extract portion
concat(arr) — join arrays
map(fn) — transform each
filter(fn) — keep matching
reduce(fn, init) — accumulate
find(fn) — first match
findIndex(fn) — index of first match
some(fn) — any match?
every(fn) — all match?
includes(x) — contains?
indexOf(x) — first index
flat(depth) — flatten
flatMap(fn) — map + flatten 1 levelPart 8: Objects — Essential Operations
Example
// Create
const obj = { a: 1, b: 2 };
const obj2 = new Object({ a: 1 });
const obj3 = Object.create(proto);
// Read
obj.a // dot notation
obj["a"] // bracket notation
const { a } = obj; // destructuring
// Add/Update
obj.c = 3;
Object.assign(obj, { d: 4 });
const merged = { ...obj, e: 5 };
// Delete
delete obj.a;
// Iterate
Object.keys(obj) // ["b", "c", "d", "e"]
Object.values(obj) // [2, 3, 4, 5]
Object.entries(obj) // [["b",2], ...]
for (const key in obj) {} // includes prototype keys!
// Check
"b" in obj // true (includes prototype)
obj.hasOwnProperty("b") // true (own only)
// Clone
const shallow = { ...obj };
const deep = structuredClone(obj); // ES2022
// Freeze / Seal
Object.freeze(obj) // no changes at all (shallow)
Object.seal(obj) // no add/delete, can modify
Part 9: Promises & Async/Await
Promise Basics
Example
// Create
const p = new Promise((resolve, reject) => {
// executor runs SYNCHRONOUSLY
setTimeout(() => resolve("data"), 1000);
});
// Consume
p.then(data => console.log(data))
.catch(err => console.error(err))
.finally(() => console.log("done"));
// Static methods
Promise.resolve("instant value")
Promise.reject(new Error("instant fail"))
Promise.all([p1, p2]) // all or fail fast
Promise.allSettled([p1, p2]) // wait for all
Promise.race([p1, p2]) // first to settle
Promise.any([p1, p2]) // first to fulfill
async/await
Example
async function fn() {
// async always returns a Promise
const data = await fetchSomething(); // pauses fn
return data; // resolves the Promise
}
// Error handling
async function safe() {
try {
return await riskyOperation();
} catch (err) {
console.error(err.message);
return null;
}
}
// Parallel
const [a, b] = await Promise.all([fetch1(), fetch2()]);
// Sequential
const a = await step1();
const b = await step2(a);
Part 10: ES6+ Features
Destructuring
Example
// Array
const [a, b, ...rest] = [1, 2, 3, 4, 5];
const [,, third] = arr; // skip with commas
// Object
const { name, age = 25, city: location } = user;
const { a: { b: deepVal } } = nested;
// Swap
[x, y] = [y, x];
// Function params
function fn({ name, role = "user" } = {}) {}
Spread & Rest
Example
// Spread (expand)
const arr2 = [...arr1, ...arr3];
const obj2 = { ...obj1, override: "value" };
Math.max(...numbers);
// Rest (collect)
function fn(first, ...rest) {}
const { a, ...remaining } = obj;
Map, Set, WeakMap, WeakSet
Example
// Map — any key type, preserves insertion order
const map = new Map();
map.set("key", "value");
map.set(obj, "object as key!");
map.get("key");
map.has("key");
map.size;
// Set — unique values
const set = new Set([1, 2, 2, 3, 3]);
// Set {1, 2, 3}
[...new Set(arr)] // deduplicate array
// WeakMap/WeakSet — keys are weakly held (GC-friendly)
// Use for: private data, caching, DOM associations
Part 11: Classes (ES6+)
Example
class EventEmitter {
#listeners = {}; // private field (ES2022)
on(event, fn) {
(this.#listeners[event] ??= []).push(fn);
return this;
}
emit(event, ...args) {
this.#listeners[event]?.forEach(fn => fn(...args));
return this;
}
static create() {
return new EventEmitter();
}
}
class SpecialEmitter extends EventEmitter {
constructor() {
super();
this.type = "special";
}
}
const emitter = new SpecialEmitter();
emitter.on("click", data => console.log("Clicked:", data));
emitter.emit("click", { x: 100, y: 200 });
Output
Clicked: { x: 100, y: 200 }Part 12: Error Handling
Example
// Basic
try {
const json = JSON.parse("bad json");
} catch (err) {
if (err instanceof SyntaxError) {
console.log("Parse error:", err.message);
} else {
throw err; // re-throw unexpected errors
}
} finally {
cleanup(); // always runs
}
// Custom errors
class AppError extends Error {
constructor(message, code, statusCode = 500) {
super(message);
this.name = "AppError";
this.code = code;
this.statusCode = statusCode;
}
}
// Async error handling
process.on("unhandledRejection", (reason) => {
console.error("Unhandled:", reason);
});
window.addEventListener("unhandledrejection", (e) => {
console.error(e.reason);
});
Part 13: DOM Essentials
Example
// Query
document.querySelector("#id")
document.querySelectorAll(".class")
element.closest(".parent") // traverse up
// Modify
element.textContent = "text";
element.innerHTML = "<b>html</b>";
element.setAttribute("data-id", "1");
element.dataset.id // access data- attributes
element.classList.add/remove/toggle/contains/replace
// Events
element.addEventListener("click", handler, { once: true });
element.removeEventListener("click", handler);
// Event delegation (efficient)
document.body.addEventListener("click", (e) => {
if (e.target.matches(".btn")) handleButtonClick(e);
});
// Create & insert
const el = document.createElement("div");
parent.append(el); // after last child
parent.prepend(el); // before first child
sibling.before(el); // before sibling
sibling.after(el); // after sibling
el.remove(); // remove self
Part 14: Modules
js example
// Named exports
export const PI = 3.14;
export function add(a, b) { return a + b; }
export class Calculator {}
// Default export (one per file)
export default class App {}
// Import
import { PI, add } from "./math.js";
import App from "./app.js";
import * as Math from "./math.js";
import { add as sum } from "./math.js";
// Dynamic import (lazy loading)
const module = await import("./heavy.js");
module.default();One-Shot Memory Map 🗺️
Example
JAVASCRIPT
├── Types: number, string, boolean, null, undefined, symbol, bigint, object
├── Scope: global → function → block → module
├── Hoisting: var(undefined), function(full), let/const(TDZ)
├── Closures: function + lexical env → private state
├── this: default/method/new/explicit/arrow
├── Prototype: [[Proto]] chain → inherited methods
├── Async:
│ ├── Callbacks → Promises → async/await
│ └── Event Loop: sync → microtasks → macrotasks
├── ES6+: class, arrow, destructure, spread, Map/Set, modules
└── Patterns: closure, module, factory, observer, memoize, curry
Continue the lesson path
Study next in this module
01NotesImportant JavaScript Concepts Every Developer Must Know in 2026Master the most important JavaScript concepts: closures, hoisting, prototype, event loop, scope, async/await, coercion, and ES6+. Deeply explained with examples and output.02NotesJavaScript Quick Revision Notes — Interview Prep in 30 Minutes 2026Complete JavaScript quick revision notes covering all important concepts for interviews and exams. Rapid-fire key concepts with code examples and outputs for last-minute preparation.03NotesJavaScript Cheat Sheet 2026 — Complete Quick ReferenceA comprehensive JavaScript cheat sheet covering variables, data types, operators, strings, arrays, objects, functions, control flow, DOM, events, async programming, ES6+ features, error handling, and useful patterns. Perfect quick reference for beginners and experienced developers.04Mini ProjectsBuild a JavaScript Notes App - Step by Step Project TutorialLearn to build a notes app in JavaScript with create, edit, delete, search, pin, and localStorage persistence. Covers markdown preview and color coding.