โšก JavaScript Complete Mastery

Interactive Visual Guide with Real-Life Examples & Theory

JavaScript Topics Coverage

Total Topics

16

Comprehensive coverage

Interview Questions

50+

Most commonly asked

๐ŸŽ“ What is JavaScript?

Simple Explanation: JavaScript is like a magic wand for web pages. It makes websites interactive and responsive to what you do.

Think of it like this:

  • ๐Ÿ“„ HTML = The structure (like bones)
  • ๐ŸŽจ CSS = The appearance (like skin and clothes)
  • โšก JavaScript = The behavior and interaction (like muscles and brain)

๐ŸŒ Real-Life Example

Scenario: You're using Facebook and scrolling through posts.

  • HTML created the page structure
  • CSS made it look beautiful
  • JavaScript handles when you click "Like" button โ†’ it counts increase without reloading

Another Example: Netflix search bar

  • As you type, JavaScript filters and shows matching movies
  • It happens instantly without page refresh
  • That's the power of JavaScript!

๐Ÿ“š What are Variables?

Simple Explanation: Variables are like labeled boxes where you store information.

Imagine you have a box labeled "Name" where you put "John". Whenever you need John's name, you just look in that box!

๐Ÿช Real-Life Example: Coffee Shop

Without Variables: Barista writes down "John needs 2 cappuccinos" every single time he orders. Messy!

With Variables:

  • const customerName = "John" - Remember customer name once
  • let ordersCount = 2 - Keep track of how many orders
  • Now you can use these stored values anytime!

var vs let vs const - Simple Comparison

Feature var (Old Way) let (Better) const (Best)
Scope Whole function ๐ŸŒ Just that block ๐Ÿ“ฆ Just that block ๐Ÿ“ฆ
Can Change Value? โœ… Yes โœ… Yes โŒ No (Locked!)
Can Declare Again? โœ… Yes (Messy!) โŒ No โŒ No
Best For? Legacy code only โŒ Values that change โœ… Values that don't change โœ…โœ…

๐Ÿšซ var (Don't Use!)

Problem: Can be confusing - it spreads across the whole function

var username = "Alice"; if (true) { var username = "Bob"; } console.log(username); // Output: "Bob" (Changed outside block!)

Why bad: Changes outside the block affect the whole function. Confusing!

โœ… let (Use This!)

Solution: Stays only in its block, safer to use

let username = "Alice"; if (true) { let username = "Bob"; } console.log(username); // Output: "Alice" (Safe!)

Why good: Changes inside block stay inside. Clean!

โญ const (Use by Default!)

Best Practice: Use this for values you won't change

const PI = 3.14159; const name = "Charlie"; // Try to change? name = "David"; // Error!

Why best: Locks value, prevents accidental changes

๐Ÿ“Š Data Types

JavaScript can store different types of information:

42 // Number "Hello" // String true // Boolean undefined // Not defined yet null // Empty/nothing {name: "John"} // Object [1,2,3] // Array

๐ŸŽฏ When to Use What?

Start Your Code Like This:

  • ๐Ÿ‘‰ Use const by default (for most values)
  • ๐Ÿ‘‰ Use let when value will change (like counters)
  • ๐Ÿ‘‰ NEVER use var in modern code

Real Example:

const birthYear = 1990; // Never changes let age = 34; // Will change every year! const name = "Alice"; // Never changes

๐Ÿงฎ What are Operators?

Simple Explanation: Operators are like action buttons. They do things with your values.

Just like a calculator has buttons (+, -, ร—, รท), JavaScript has operators (+ - * / && || etc.)

๐Ÿ’ฐ Real-Life Example: Store Cashier

Arithmetic Operators:

  • Item costs $10, I buy 3 โ†’ Multiply: 10 ร— 3 = $30
  • I pay $50 โ†’ Subtract: 50 - 30 = $20 change
  • Total bill with tax โ†’ Add: 30 + 5 = $35

Comparison Operators:

  • Is my age >= 18? (For voting eligibility)
  • Does my password == entered password? (For login)
  • Is price < $10? (Within budget?)

Logical Operators:

  • If age >= 18 AND has ID โ†’ Allow entry
  • If has credit card OR has cash โ†’ Can pay
  • If NOT raining โ†’ Go outside

โž• Arithmetic Operators

Do math with numbers:

10 + 5 // 15 (Add) 10 - 5 // 5 (Subtract) 10 * 3 // 30 (Multiply) 10 / 2 // 5 (Divide) 10 % 3 // 1 (Remainder) 2 ** 3 // 8 (Power)

๐Ÿ”— Comparison Operators

Compare two values (returns true/false):

5 > 3 // true (Greater) 5 < 3 // false (Less) 5 >= 5 // true (Greater or equal) 5 == "5" // true (Same value) 5 === "5" // false (Different type!) 5 != "5" // false

๐Ÿง  Logical Operators

Combine conditions (for decisions):

true && true // true (AND: both true?) true || false // true (OR: any true?) !true // false (NOT: opposite) // Real example: age >= 18 && hasLicense // Can drive?

โšก Important Warning!

The == vs === Problem:

5 == "5" // true (converts type!) 5 === "5" // false (strict check) // Always use === ! if (age === 18) { // Good! if (age == 18) { // Bad! Can cause bugs

๐Ÿšจ Rule: Always use === to avoid unexpected surprises!

๐Ÿ’ก Key Takeaway: Use === for strict comparison, && for AND logic, || for OR logic. These are the most important operators you'll use daily!

๐Ÿ”ง What is a Function?

Simple Explanation: A function is like a recipe or a machine. You give it ingredients (inputs), it does something, and gives you a result (output).

You can use the same recipe many times without rewriting it each time!

๐Ÿ• Real-Life Example: Pizza Machine

Function = Pizza Making Machine

  • Input (Parameters): Dough, sauce, cheese, toppings
  • Process (Function body): Mix, spread, bake
  • Output (Return): Fresh hot pizza!

Code Version:

function makePizza(dough, sauce, cheese) { // Do something const pizza = "Mix and bake..."; return pizza; // Give result back } // Use it multiple times: makePizza("wheat", "tomato", "mozzarella"); makePizza("thin", "white", "cheddar");

๐Ÿ“ Function Declaration

Traditional way: Define function first, then use it

function greet(name) { return `Hello, ${name}!`; } greet("Alice"); // "Hello, Alice!"

Pro: Can use BEFORE defining (hoisting)

๐Ÿ“ฆ Function Expression

Modern way: Store function in a variable

const greet = function(name) { return `Hello, ${name}!`; }; greet("Bob"); // "Hello, Bob!"

Pro: More flexible, can pass around

๐ŸŽฏ Arrow Function (Newest!)

Shortest way: Quick and clean syntax

const greet = (name) => `Hello, ${name}!`; greet("Charlie"); // "Hello, Charlie!" // Even shorter for single parameter: const square = x => x * x;

Pro: Very clean and modern

๐Ÿ” Closures - Power Feature!

What: Function remembers variables from where it was created

function makeCounter() { let count = 0; return function() { count++; return count; }; } const counter = makeCounter(); counter(); // 1 counter(); // 2 counter(); // 3

Magic: count stays private but persists!

๐Ÿฆ Closure Real Example: Bank Account

Without Closure: Anyone can see and change your balance. Dangerous!

With Closure:

  • balance variable is hidden (private)
  • Only deposit/withdraw functions can access it
  • Super secure!
function createAccount(initialBalance) { let balance = initialBalance; // Private! return { deposit: (amount) => balance += amount, withdraw: (amount) => balance -= amount, getBalance: () => balance }; } const myAccount = createAccount(1000); myAccount.deposit(500); // 1500 myAccount.withdraw(200); // 1300

๐ŸŽฏ What is Scope?

Simple Explanation: Scope is like "who can see what". A variable created in a box can only be seen inside that box.

Imagine variables are secrets - some are global (everyone knows), some are local (only you know).

๐Ÿข Real-Life Example: Office Building

Global Scope: Receptionist at front desk - Everyone sees them

Function Scope: Manager in their office - Only people in that office see them

Block Scope: Stuff in your drawer - Only you see it when you open it

const receptionist = "Linda"; // Global - everyone knows function officeWork() { const manager = "Bob"; // Function scope - only here if (true) { const secret = "hidden"; // Block scope - only in this if } // Can't access 'secret' here! }

๐ŸŒ Global Scope

Available everywhere in your code:

const globalVar = "I'm everywhere!"; function test() { console.log(globalVar); // โœ… Can access } test();

๐Ÿ”’ Function Scope

Only available inside the function:

function test() { const localVar = "Only here!"; console.log(localVar); // โœ… Can access } console.log(localVar); // โŒ Error! Not here

๐Ÿ“ฆ Block Scope

Only available in that block {}:

if (true) { const blockVar = "Only in block"; // โœ… Can access } console.log(blockVar); // โŒ Error! Out of block

โš ๏ธ Hoisting - The Surprise!

JavaScript moves declarations to top (weird!):

console.log(x); // undefined (not error!) var x = 5; // ^^^ JavaScript actually runs like: var x; // Moved to top console.log(x); // undefined x = 5; // Then assigned
๐Ÿ’ก Remember: Use const and let (not var) to avoid confusing hoisting issues!

๐Ÿ“ฆ What is an Object?

Simple Explanation: An object is like a real-world thing with properties and abilities.

Just like a car has: color (property), speed (property), and can drive/stop (abilities/methods)

๐Ÿš— Real-Life Example: Car Object

Properties (What it has):

  • Color: "Red"
  • Brand: "Toyota"
  • Speed: 0

Methods (What it can do):

  • accelerate() - Speed up
  • brake() - Slow down
  • honk() - Make noise
const myCar = { color: "Red", brand: "Toyota", speed: 0, accelerate() { this.speed += 10; }, brake() { this.speed = 0; } }; myCar.accelerate(); // Speed = 10 myCar.brake(); // Speed = 0

๐Ÿ“‹ Object Literal

Most common way - just like a dictionary:

const person = { name: "Alice", age: 25, city: "New York", greet() { return `Hi, I'm ${this.name}`; } }; // Access properties: person.name; // "Alice" person["age"]; // 25 // Call method: person.greet(); // "Hi, I'm Alice"

๐Ÿ—๏ธ Useful Object Methods

Do things with objects:

const obj = {a: 1, b: 2}; Object.keys(obj); // ["a", "b"] Object.values(obj); // [1, 2] Object.entries(obj); // [["a", 1], ["b", 2]]

๐Ÿ”— this Keyword

"this" means the object itself:

const person = { name: "Bob", introduce() { // 'this' = person return `I'm ${this.name}`; } }; person.introduce(); // "I'm Bob"

๐Ÿ“ฆ Copying Objects

Be careful - objects are tricky!:

const obj1 = {name: "Alice"}; const obj2 = obj1; // Wrong! Same reference obj2.name = "Bob"; console.log(obj1.name); // "Bob"! Changed both // Right way - spread operator: const obj3 = { ...obj1 }; obj3.name = "Charlie"; console.log(obj1.name); // Still "Alice"

๐Ÿ“š What is an Array?

Simple Explanation: An array is like a list or shopping list. You can store multiple items in order.

Instead of: item1, item2, item3... you have: [item1, item2, item3]

๐Ÿ›’ Real-Life Example: Shopping List

Array = Shopping List

  • Position 0: Apples
  • Position 1: Milk
  • Position 2: Bread
  • Position 3: Eggs
const shoppingList = [ "Apples", "Milk", "Bread", "Eggs" ]; shoppingList[0]; // "Apples" (First item) shoppingList[2]; // "Bread" (Third item) shoppingList.length; // 4 (How many items)

Note: Counting starts at 0! (Programmer habit!)

๐Ÿ”„ Mutating Methods (Changes List)

These change the original array:

let arr = [1, 2, 3]; arr.push(4); // Add end [1,2,3,4] arr.pop(); // Remove end [1,2,3] arr.shift(); // Remove start [2,3] arr.unshift(0); // Add start [0,2,3] arr.reverse(); // Flip [3,2,0] arr.sort(); // Sort [0,2,3]

โœจ Non-Mutating Methods (Safe!)

These create new array, don't change original:

const arr = [1, 2, 3]; arr.map(x => x*2); // [2,4,6] (original stays [1,2,3]) arr.filter(x => x > 1); // [2,3] arr.slice(1, 3); // [2,3] (original untouched)

๐ŸŽฏ map() - Transform Each Item

What: Do the same thing to every item in list

Analogy: Give each student 5 bonus points

const scores = [80, 90, 85]; const bonusScores = scores.map( score => score + 5 ); // [85, 95, 90]

๐Ÿ” filter() - Keep Only Some

What: Keep only items that pass a test

Analogy: Keep only passing students (>70)

const scores = [80, 50, 95, 60]; const passed = scores.filter( score => score > 70 ); // [80, 95]

โž• reduce() - Combine All

What: Combine all items into one result

Analogy: Add all scores to get total

const scores = [80, 90, 85]; const total = scores.reduce( (sum, score) => sum + score, 0 ); // 255 (80 + 90 + 85)

๐Ÿ”Ž find() - Get First Match

What: Find first item that matches

Analogy: Find first student named "Alice"

const students = [ {name: "Bob", age: 20}, {name: "Alice", age: 21} ]; const found = students.find( s => s.name === "Alice" ); // {name: "Alice", age: 21}

๐Ÿ’ณ Real Example: Credit Card Transactions

const transactions = [ {id: 1, amount: 50, type: "food"}, {id: 2, amount: 100, type: "movie"}, {id: 3, amount: 200, type: "food"} ]; // Get all food expenses const foodExpenses = transactions .filter(t => t.type === "food") .map(t => t.amount); // [50, 200] // Total spent const totalSpent = transactions .map(t => t.amount) .reduce((sum, amount) => sum + amount, 0); // 350

๐ŸŽจ What is DOM?

Simple Explanation: DOM = Document Object Model. It's the HTML page turned into JavaScript objects that you can control.

Think of it as: "JavaScript's way of controlling the web page"

๐ŸŽญ Real-Life Example: Theatre Stage

Without JavaScript: The stage is static. What you see is what you get.

With JavaScript/DOM: You can:

  • Change actor's costume (change styles)
  • Move them to different position (change position)
  • Add new actors on stage (create elements)
  • Remove actors (delete elements)
  • Respond when audience claps (event handling)

๐ŸŽฏ Select Elements

Find HTML elements to control:

// Find by ID document.getElementById("myId"); // Find by class document.querySelector(".myClass"); // Find all by class document.querySelectorAll(".myClass"); // Find by tag document.getElementsByTagName("button");

โœ๏ธ Modify Elements

Change what the element looks like:

const btn = document.getElementById("myBtn"); // Change text btn.textContent = "Click me!"; // Change HTML btn.innerHTML = "<b>Bold</b>"; // Change style btn.style.backgroundColor = "blue"; btn.style.color = "white"; // Add class btn.classList.add("active");

๐ŸŽช Event Listeners

Listen for user actions:

const btn = document.getElementById("myBtn"); // When clicked, do something btn.addEventListener("click", () => { console.log("Button clicked!"); }); // Other events: // "mouseover", "mouseout", "input", "change"

๐Ÿ—๏ธ Create & Delete

Add or remove elements:

// Create new element const newDiv = document.createElement("div"); newDiv.textContent = "Hello!"; // Add to page document.body.appendChild(newDiv); // Remove element newDiv.remove();

๐ŸŽฌ Real Example: Movie List App

HTML (Stage):

<button id="addBtn">Add Movie</button> <ul id="movieList"></ul>

JavaScript (Controller):

const addBtn = document.getElementById("addBtn"); const list = document.getElementById("movieList"); addBtn.addEventListener("click", () => { // Create new movie item const item = document.createElement("li"); item.textContent = "New Movie"; // Add to list list.appendChild(item); });

โณ What is Async?

Simple Explanation: Async means "not right now". Your code doesn't have to wait for slow things (like downloading data).

Instead of blocking and waiting, JavaScript can do other stuff while waiting!

โ˜• Real-Life Example: Coffee Shop

Without Async (Synchronous): You order coffee, cashier makes it while you wait, blocking everyone behind you. Terrible!

With Async:

  • You order coffee
  • Cashier says "Ready in 5 minutes" (Promise)
  • You sit down and wait
  • When ready, they call your name (callback)
  • Other customers can order while you wait

๐Ÿ“ž Callbacks (Old Way)

What: Function to run when done:

function fetchData(callback) { setTimeout(() => { const data = "User data"; callback(data); }, 2000); // Wait 2 seconds } fetchData((data) => { console.log(data); // Runs after 2 seconds });

โœ… Promises (Better)

What: A promise for future value

const myPromise = new Promise( (resolve, reject) => { setTimeout(() => { resolve("Data ready!"); }, 2000); } ); myPromise .then(data => console.log(data)) .catch(err => console.log(err));

โณ Async/Await (Best!)

What: Looks like normal code but waits for promises

async function main() { try { const data = await fetchData(); console.log(data); } catch (error) { console.log(error); } } main();

Why best: Reads like normal code!

๐ŸŒ Fetch API

What: Download data from internet

async function getUsers() { const response = await fetch("/api/users"); const data = await response.json(); console.log(data); } getUsers();

๐ŸŽฎ Real Example: Video Game Loading

async function startGame() { // While loading, show spinner showSpinner(true); try { // Wait for player data to download const playerData = await downloadPlayerData(); // Wait for map to load const mapData = await downloadMap(); // All ready! Hide spinner, start game showSpinner(false); playGame(playerData, mapData); } catch (error) { console.log("Download failed!", error); } }

Deep Dive: Industry Concepts

Promises (Deep & Practical)

A Promise represents a value that will be available now, later, or never.

States

  • โณ Pending
  • โœ… Fulfilled
  • โŒ Rejected

Visual Flow

Request โ†’ Pending โ†’ (Resolve โœ” / Reject โœ–)

const orderFood = new Promise((resolve, reject) => {
  setTimeout(() => {
    const success = true;
    success ? resolve("๐Ÿ• Food Delivered") : reject("โŒ Order Failed");
  }, 2000);
});

orderFood
  .then(res => console.log(res))
  .catch(err => console.error(err));

async / await

Modern syntax for handling Promises that reads like synchronous code. Used **everywhere** in modern frameworks (React, Node, etc.).

async function loadUser() {
  try {
    const res = await fetch('/api/user');
    const data = await res.json();
    console.log(data);
  } catch (err) {
    console.error(err);
  }
}

Rule: `await` only works inside an `async` function.

Fetch API (Real API Calls)

The standard browser API used to **communicate with backend servers**.

GET Example

const getPosts = async () => {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts');
  const data = await res.json();
  console.log(data);
};

POST Example

fetch('/api/login', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ email, password })
});

API + Frontend Flow

A crucial interview concept explaining how the frontend and backend interact.

User โ†’ Button Click โ†’ JS โ†’ Fetch API โ†’ Server โ†’ Response โ†’ UI Update

btn.addEventListener('click', async () => {
  const res = await fetch('/api/products');
  const data = await res.json();
  renderProducts(data);
});

The Event Loop

Explains **how JavaScript handles asynchronous code** without getting blocked.

Execution Order

  1. Call Stack
  2. Web APIs (e.g. setTimeout, fetch)
  3. Callback/Task Queue
  4. Event Loop
console.log('A');
setTimeout(() => console.log('B'), 0);
console.log('C');
// Output: A โ†’ C โ†’ B

Microtasks vs Macrotasks

The Event Loop has two queues with different priorities.

Microtasks (High Priority โšก)

  • Promise.then, .catch, .finally
  • async/await

Macrotasks (Lower Priority โณ)

  • setTimeout
  • setInterval
  • I/O operations

Rule: The Event Loop processes all available microtasks before processing the next macrotask.

Top 20 Interview Questions Explained Simply

1๏ธโƒฃ What are Closures?

Answer: Function that remembers variables from where it was created.

Example: A diary that remembers secrets only you can see.

2๏ธโƒฃ What is Hoisting?

Answer: JavaScript moves declarations to top before running.

Example: Books sorted to top of shelf automatically.

3๏ธโƒฃ Explain 'this' Keyword

Answer: 'this' = the object that owns the method.

Example: In "car.drive()", 'this' = car object.

4๏ธโƒฃ var vs let vs const?

Answer: Use const (default), let (if changing), never var.

Example: const name, let count, never var x.

5๏ธโƒฃ What is Scope?

Answer: Who can see what variables.

Example: Parents can see house, kids can see their room only.

6๏ธโƒฃ == vs ===?

Answer: === is strict (type matters), == converts types.

Example: 5 === "5" is false, 5 == "5" is true.

7๏ธโƒฃ What is callback?

Answer: Function passed to another function to run later.

Example: Button.addEventListener("click", callback)

8๏ธโƒฃ What is Promise?

Answer: Promise for future value (will resolve or reject).

Example: "Promise to call you back in 5 mins".

9๏ธโƒฃ What is async/await?

Answer: Clean way to handle promises.

Example: const data = await fetch(url).

๐Ÿ”Ÿ What are Array methods?

Answer: map, filter, reduce to transform arrays.

Example: [1,2,3].map(x => x*2) = [2,4,6].

1๏ธโƒฃ1๏ธโƒฃ What is Destructuring?

Answer: Extract values from arrays/objects quickly.

Example: const {name, age} = person.

1๏ธโƒฃ2๏ธโƒฃ What is Event Delegation?

Answer: Listen to parent instead of all children.

Example: Listen to list, handle all item clicks.

1๏ธโƒฃ3๏ธโƒฃ What is Spread Operator?

Answer: Expand array/object into individual items.

Example: {...obj, name: "new"}

1๏ธโƒฃ4๏ธโƒฃ What is Prototypes?

Answer: Objects inherit from prototypes.

Example: All cars share "drive" method from prototype.

1๏ธโƒฃ5๏ธโƒฃ What is JSON?

Answer: Text format to store/send data.

Example: JSON.parse(), JSON.stringify().

1๏ธโƒฃ6๏ธโƒฃ What is DOM?

Answer: JavaScript's way to control web page.

Example: document.getElementById, classList.add()

1๏ธโƒฃ7๏ธโƒฃ What is Event Bubbling?

Answer: Event goes UP from child to parent.

Example: Click on button โ†’ click on parent โ†’ click on body.

1๏ธโƒฃ8๏ธโƒฃ What is try/catch?

Answer: Handle errors gracefully.

Example: try { riskyCode } catch { handle }

1๏ธโƒฃ9๏ธโƒฃ What is call/apply/bind?

Answer: Set 'this' value explicitly.

Example: func.call(obj), func.apply(obj, [args])

2๏ธโƒฃ0๏ธโƒฃ What is Ternary Operator?

Answer: Quick if/else: condition ? true : false

Example: age >= 18 ? "Adult" : "Minor"

๐ŸŒŸ Final Tips for Interview Success

โœ… DO's

  • โœ“ Use console.log() to debug
  • โœ“ Test with small examples
  • โœ“ Explain your thinking out loud
  • โœ“ Ask clarifying questions
  • โœ“ Use const by default
  • โœ“ Handle edge cases
  • โœ“ Practice daily coding
  • โœ“ Read others' code

โŒ DON'Ts

  • โœ— Don't use var (ever!)
  • โœ— Don't use == (use ===)
  • โœ— Don't panic if stuck
  • โœ— Don't skip error handling
  • โœ— Don't ignore warnings
  • โœ— Don't memorize (understand)
  • โœ— Don't code without thinking
  • โœ— Don't forget about closures

๐Ÿ’ช How to Ace the Interview

  1. Understand, don't memorize: Know WHY not just WHAT
  2. Use real examples: "Like a coffee shop, this variable..."
  3. Write code: Practice 1 hour daily
  4. Explain clearly: Make interviewer understand your thinking
  5. Handle errors: Think about what can go wrong
  6. Optimize: "Can we make this faster/simpler?"
  7. Ask questions: "Should I handle null inputs?"

๐Ÿš€ What is Modern JavaScript (ES6+)?

Simple Explanation: ES6 (ECMAScript 2015) was a huge update to JavaScript that added many features to make code cleaner, more powerful, and easier to write. We call these "modern" features.

Think of it as getting a big software update for your favorite app - suddenly it has all these cool new shortcuts and abilities you can't live without!

๐Ÿ“ฑ Real-Life Example: Smartphone Update

Your old phone could make calls and send texts. After a big software update (like ES6), it can now:

  • Use Face ID (like class syntax for easier objects)
  • Have pre-written text responses (like Template Literals)
  • Automatically set a default alarm volume (like Default Parameters)
  • Keep a list of unique contacts without duplicates (like a Set)

These modern features don't change the phone's core purpose, but they make it much better to use every day. The same is true for ES6+ in JavaScript.

๐Ÿ›๏ธ class Syntax

A cleaner way to create objects and handle inheritance. It's "syntactic sugar" over the old prototype system.

class Car { constructor(brand) { this.brand = brand; } present() { return 'I have a ' + this.brand; } } const mycar = new Car("Ford"); console.log(mycar.present()); // "I have a Ford"

Use for: Creating reusable object blueprints, essential in frameworks like React.

โœ๏ธ Template Literals

Allows embedding expressions inside strings using back-ticks (``) and ${}. Makes creating complex strings much easier.

const name = "Alice"; const age = 30; // Old way const messageOld = "Hello, " + name + "! You are " + age + " years old."; // Modern way const messageNew = `Hello, ${name}! You are ${age} years old.`; console.log(messageNew);

Use for: Any time you need to build a string from variables. Cleaner and more readable.

โš™๏ธ Default Parameters

Allows you to initialize a function with default values if no value or undefined is passed.

function greet(name = 'Guest') { console.log(`Hello, ${name}!`); } greet("Bob"); // "Hello, Bob!" greet(); // "Hello, Guest!"

Use for: Making functions more robust and avoiding errors from missing arguments.

๐Ÿงฉ Map & Set

New data structures for more specific use cases.

Set

A collection of unique values. No duplicates allowed!

const mySet = new Set([1, 1, 2, 3, 2]); console.log([...mySet]); // [1, 2, 3]

Map

Like an object, but keys can be any type (not just strings). Maintains insertion order.

Destructuring

A convenient way of extracting multiple properties from an object or items from an array.

Object Destructuring

const user = { name: 'Sahil', age: 22 };
const { name, age } = user;
console.log(name); // 'Sahil'

Array Destructuring

const [first, second] = [10, 20];
console.log(first); // 10

Spread & Rest Operators

The `...` syntax can be used for two different (but related) purposes.

Spread (...)

Expands an iterable (like an array or object) into individual elements. Used for copying or merging.

const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5]; // [1, 2, 3, 4, 5]

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

Rest (...)

Bundles the "rest" of the elements into an array. Used in function arguments.

function sum(...nums) {
  return nums.reduce((a, b) => a + b);
}
sum(1, 2, 3, 4); // Returns 10

JavaScript Modules (ESM)

The standard way to organize your code into separate, reusable files.

Exporting

You can `export` functions, variables, or classes from a file.

// In file: math.js
export const add = (a, b) => a + b;
export const PI = 3.14;

Importing

Use `import` to use the exported code in another file.

// In file: main.js
import { add, PI } from './math.js';

console.log(add(2, 3)); // 5

To make this work in the browser, you need to add `type="module"` to your script tag: <script type="module" src="main.js"></script>

๐Ÿ’พ Browser Storage

Modern browsers provide ways for web pages to store data on a user's computer, which can persist even after the browser is closed. This is essential for features like remembering user preferences, keeping users logged in, or saving shopping cart contents.

๐Ÿ”Ÿ LocalStorage & SessionStorage

The two most common mechanisms for storing simple key-value pairs.

Why are they used?

  • To save login information or user tokens.
  • To remember a user's theme preference (e.g., 'dark' or 'light' mode).
  • To store shopping cart data before a user checks out.

Example

// Save data localStorage.setItem('theme', 'dark'); // Get data const currentTheme = localStorage.getItem('theme'); console.log(currentTheme); // "dark" // Remove data localStorage.removeItem('theme'); // Clear all data localStorage.clear();
LocalStorage vs. SessionStorage:
- LocalStorage: Persists until the user manually clears the browser cache.
- SessionStorage: Only persists for the duration of the page session. The data is cleared when the tab is closed.

โšก Performance Optimization

In interactive applications, some events can fire very rapidly (like resizing a window, scrolling, or typing in a search box). Handling every single event can be computationally expensive and lead to a slow, unresponsive user experience. Techniques like Debounce and Throttle help us control how often we execute functions in response to these events.

Debounce

Analogy: Imagine waiting for an elevator. You press the button once. If someone else comes and presses it again before the elevator arrives, the timer resets. The elevator is only called once the button hasn't been pressed for a certain amount of time.

Use Case: A search input that makes an API call. You only want to send the request after the user has *stopped typing* for a moment, not on every single keystroke.

const debounce = (fn, delay) => { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); }; }; // Usage const handleInput = debounce(() => { console.log('Fetching search results...'); }, 500); mySearchInput.addEventListener('input', handleInput);

Throttle

Analogy: Imagine a water gun that can only be fired once every second, no matter how many times you pull the trigger in that second. It ensures a maximum rate of execution.

Use Case: Handling scroll events. You might want to update an element's position or trigger an animation based on scroll position, but you don't need to do it hundreds of times per second. Throttling to once every 100ms is much more efficient.

const throttle = (fn, delay) => { let inProgress = false; return (...args) => { if (inProgress) { return; } inProgress = true; setTimeout(() => { fn(...args); inProgress = false; }, delay); }; }; // Usage const handleScroll = throttle(() => { console.log('User is scrolling...'); }, 100); window.addEventListener('scroll', handleScroll);
Key Difference:
- Debounce: Executes the function only *after* a period of inactivity.
- Throttle: Executes the function at most *once* per specified time interval.

๐Ÿ—๏ธ Mini Projects (With Full Code)

The best way to learn is by doing. Below are mini-projects for each major JavaScript topic, complete with theory, concepts, and full runnable code. Try to build them yourself first!

1๏ธโƒฃ Variables & Functions โ€” Age Calculator

A simple app to calculate a user's age based on their birth year.

Concepts Used: const/let, function, DOM input & output.

๐Ÿงช Full Code

<!DOCTYPE html>
<html>
<body>
  <h3>Age Calculator</h3>
  <input id="year" placeholder="Enter birth year" />
  <button onclick="calcAge()">Calculate</button>
  <p id="result"></p>

  <script>
    function calcAge() {
      const year = document.getElementById('year').value;
      const age = new Date().getFullYear() - year;
      document.getElementById('result').textContent = `Your age is ${age}`;
    }
  </script>
</body>
</html>

2๏ธโƒฃ Arrays โ€” Todo List App

A classic app to manage a list of tasks. You can add new tasks and see them rendered on the screen.

Concepts Used: Array push, forEach for rendering, DOM manipulation.

๐Ÿงช Full Code

<input id="task" />
<button onclick="addTodo()">Add</button>
<ul id="list"></ul>

<script>
let todos = [];

function addTodo() {
  const task = document.getElementById('task').value;
  todos.push(task);
  render();
}

function render() {
  const ul = document.getElementById('list');
  ul.innerHTML = '';
  todos.forEach(t => {
    const li = document.createElement('li');
    li.textContent = t;
    ul.appendChild(li);
  });
}
</script>

3๏ธโƒฃ Objects โ€” User Profile Card

Displays a user's profile information from an object.

Concepts Used: Object literals, this keyword, methods on objects.

๐Ÿงช Full Code

<div id="card"></div>
<script>
const user = {
  name: 'Sahil',
  role: 'Frontend Developer',
  show() {
    document.getElementById('card').innerHTML = `
      <h3>${this.name}</h3>
      <p>${this.role}</p>`;
  }
};
user.show();
</script>

4๏ธโƒฃ DOM & Events โ€” Counter App

A simple counter with increment, decrement buttons.

Concepts Used: addEventListener, textContent, state management.

๐Ÿงช Full Code

<button id="dec">-</button>
<span id="count">0</span>
<button id="inc">+</button>

<script>
let count = 0;
const display = document.getElementById('count');

document.getElementById('inc').onclick = () => display.textContent = ++count;
document.getElementById('dec').onclick = () => display.textContent = --count;
</script>

5๏ธโƒฃ Promises โ€” Fake API Loader

Simulates an API call that takes time to complete, showing a loading message and then the data.

Concepts Used: new Promise, setTimeout, then().

๐Ÿงช Full Code

<p id="status">Loading...</p>
<script>
const fakeAPI = new Promise(res => setTimeout(() => res('Data Loaded'), 2000));

fakeAPI.then(data => document.getElementById('status').textContent = data);
</script>

6๏ธโƒฃ Async/Await โ€” API Simulation

Uses the modern async/await syntax to handle an asynchronous operation.

Concepts Used: async, await, Promise handling.

๐Ÿงช Full Code

<p id="data"></p>
<script>
async function load() {
  const res = await new Promise(r => setTimeout(() => r('User Data'), 1500));
  document.getElementById('data').textContent = res;
}
load();
</script>

7๏ธโƒฃ Fetch API โ€” Product List

Fetches a list of products from a real online API and displays them.

Concepts Used: fetch, then(), json(), rendering API data.

๐Ÿงช Full Code

<ul id="products"></ul>
<script>
fetch('https://fakestoreapi.com/products')
  .then(r => r.json())
  .then(data => {
    document.getElementById('products').innerHTML =
      data.slice(0,5).map(p => `<li>${p.title}</li>`).join('');
  });
</script>

8๏ธโƒฃ Local Storage โ€” Theme Switcher

A button to toggle between light and dark themes, remembering the user's choice.

Concepts Used: localStorage.setItem, localStorage.getItem.

๐Ÿงช Full Code

<button onclick="toggle()">Toggle Theme</button>
<script>
function toggle() {
  const theme = localStorage.getItem('theme') === 'dark' ? 'light' : 'dark';
  localStorage.setItem('theme', theme);
  document.body.style.background = theme === 'dark' ? '#111' : '#fff';
}
// Apply saved theme on load
if (localStorage.getItem('theme')) {
    document.body.style.background = localStorage.getItem('theme') === 'dark' ? '#111' : '#fff';
}
</script>

9๏ธโƒฃ Debounce โ€” Search Input

Logs the user's input to the console only after they have stopped typing for 500ms.

Concepts Used: Debounce pattern, setTimeout, clearTimeout.

๐Ÿงช Full Code

<input id="search" placeholder="Search and check the console" />
<script>
let timer;
document.getElementById('search').addEventListener('input', e => {
  clearTimeout(timer);
  timer = setTimeout(() => console.log(e.target.value), 500);
});
</script>

โ“ Interview Q&A

A condensed list of the most frequently asked JavaScript interview questions, organized by category. Use this as a checklist to test your knowledge.

๐Ÿ”น Basics

  1. What is JavaScript?
  2. Difference between var, let, const?
  3. What is hoisting?
  4. What is scope?
  5. What is a closure?
  6. What is the difference between `==` and `===`?
  7. What is NaN?
  8. What are primitive vs non-primitive data types?
  9. What does `typeof` do?
  10. What is type coercion?

๐Ÿ”น Functions & Objects

  1. What is the difference between a function declaration and expression?
  2. What are arrow functions? How are they different?
  3. Explain the `this` keyword.
  4. Explain call, apply, and bind.
  5. What is a prototype and prototypal inheritance?
  6. What is object destructuring?
  7. What is the spread operator?
  8. What is the rest operator?
  9. What is the difference between a shallow and deep copy?
  10. What do `JSON.stringify` and `JSON.parse` do?

๐Ÿ”น Arrays

  1. What is the difference between `map` and `forEach`?
  2. What is the difference between `filter` and `find`?
  3. What are some use cases for `reduce`?
  4. What is the difference between `slice` and `splice`?
  5. What is the difference between `push` and `unshift`?
  6. How can you remove duplicates from an array?
  7. How do you sort an array of objects by a property?
  8. How do you flatten a nested array?
  9. What are immutable array updates?
  10. What are array-like objects?

๐Ÿ”น Async & APIs

  1. What is a callback?
  2. What is callback hell?
  3. What is a Promise?
  4. What are the states of a Promise?
  5. What is the difference between `.then` and `.catch`?
  6. What is async/await?
  7. How do you handle errors with async/await?
  8. What is the difference between Fetch and Axios?
  9. Explain the Event Loop.
  10. What is the difference between a microtask and a macrotask?
Common API Questions:
  • โœ” Difference between Promise & async/await
  • โœ” What happens if an awaited promise fails?
  • โœ” How does JS handle multiple API calls?
  • โœ” How can you optimize API calls?

๐Ÿ”น Browser & Advanced

  1. What is the DOM?
  2. What is event bubbling and capturing?
  3. What is event delegation?
  4. What is the difference between debounce and throttle?
  5. What is the difference between LocalStorage and SessionStorage?
  6. What is the difference between cookies and web storage?
  7. What is CORS?
  8. What are common causes of memory leaks?
  9. What is "strict mode"?
  10. Can you name three ES6 features?