1. var vs let vs const
Pehle JavaScript mein sirf var tha, lekin ES6 mein let aur const aaye jo better scope aur control dete hain.
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function-scoped | Block-scoped | Block-scoped |
| Reassignment | ✅ Allowed | ✅ Allowed | ❌ Not Allowed |
| Hoisting | ✅ Yes (undefined) | ⚠️ Yes (TDZ) | ⚠️ Yes (TDZ) |
| Redeclaration | ✅ Allowed | ❌ Not Allowed | ❌ Not Allowed |
🎮 Interactive Demo - Scope Testing
2. Arrow Functions & Implicit Return
Arrow functions ek concise tarika hai functions likhne ka. Ye this binding ko parent se inherit karte hain, jo React mein bahut useful hai.
🎮 Arrow Function Calculator
3. Template Literals
Template literals backticks (`) use karte hain aur string interpolation ko easy banate hain. Multi-line strings aur expressions embed kar sakte hain directly.
🎮 Template Literal Builder
4. Destructuring Objects & Arrays
Destructuring se hum objects aur arrays se values ko easily extract kar sakte hain. React props mein bahut use hota hai.
🎮 Destructuring Demo
5. Spread & Rest Operators (...)
Dono operators same symbol use karte hain (...) lekin context ke according different kaam karte hain. Spread expands, Rest collects.
🎮 Spread & Rest Visualizer
6. Array Methods (map, filter, reduce, find, some, every)
Ye methods React mein data manipulation ke liye bahut important hain. Immutable operations perform karte hain - original array change nahi hota.
🎮 Array Methods Playground
Array: [2, 4, 6, 8, 10, 15, 20, 25, 30]
7. Promises + Async/Await + Error Handling
Promises asynchronous operations handle karne ke liye use hote hain. async/await promises ko synchronous jaisa dikhata hai, making code cleaner.
🎮 Async Operations Simulator
8. Deep Copy vs Shallow Copy
Shallow copy sirf top-level copy karta hai, nested objects reference share karte hain. Deep copy complete independent copy banata hai.
🎮 Copy Behavior Visualizer
9. Optional Chaining (?.) & Nullish Coalescing (??)
Ye modern operators safely nested properties access karne aur default values set karne mein help karte hain.
🎮 Optional Chaining Demo
10. Debouncing & Throttling
Debouncing function ko tab call karta hai jab user typing/action stop kare. Throttling function ko fixed intervals pe call karta hai. Search bars aur scroll events mein use hota hai.
🎮 Live Debouncing & Throttling
Debouncing (Search): Type karo aur 500ms baad function call hoga
Throttling (Button Click): Kitna bhi click karo, har 1 second mein ek hi call
11. Classes and OOP Essentials
Classes ES6 mein aaye, React class components mein use hote the. Now mostly functional components with hooks, lekin OOP concepts samajhna important hai.
🎮 Class Creation Demo
12. Modules (import/export)
ES6 Modules code ko organize karne ka modern tarika hai. React components, utilities, aur constants ko alag files mein rakhte hain.
React mein usage:
13. Default Parameters
Default parameters se function arguments ko default values de sakte hain agar value pass nahi ki.
🎮 Default Parameters Demo
🎯 Interview Questions
Q1: What is the difference between let, const, and var?
var:
- Function-scoped (not block-scoped)
- Can be redeclared and reassigned
- Hoisted with undefined value
- Creates property on global object when declared globally
let:
- Block-scoped { }
- Cannot be redeclared, but can be reassigned
- Temporal Dead Zone (TDZ) - cannot access before declaration
- Best for variables that will change
const:
- Block-scoped { }
- Cannot be redeclared or reassigned
- Must be initialized at declaration
- Object/Array properties can still be modified (reference is constant, not content)
Q2: Explain arrow functions and when to use them in React.
Arrow Functions: Concise syntax for writing functions with lexical 'this' binding.
Key differences from regular functions:
- No own 'this' - inherits from parent scope
- Cannot be used as constructors
- No 'arguments' object
- Implicit return for single expressions
Use in React:
- Event handlers: onClick={() => handleClick()}
- Array methods: data.map(item => <Component />)
- Functional components
- Callbacks in useEffect, useState
Q3: What is the difference between map(), filter(), and reduce()? Give React examples.
map(): Transforms each element and returns new array of same length
// React: Rendering list
users.map(user => <UserCard key={user.id} user={user} />)
filter(): Returns new array with elements that pass a test
// React: Filtering active users activeUsers = users.filter(user => user.active)
reduce(): Reduces array to single value (sum, object, etc.)
// React: Calculate total price const total = cart.reduce((sum, item) => sum + item.price, 0)
Can be chained:
products .filter(p => p.inStock) .map(p => p.price) .reduce((sum, price) => sum + price, 0)
Q4: Explain Promises, async/await, and error handling in API calls.
Promises: Objects representing eventual completion/failure of async operation
Three states: Pending → Fulfilled/Rejected
Promise approach:
fetch('/api/users')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err))
.finally(() => setLoading(false))
Async/Await approach (cleaner):
async function fetchUsers() {
try {
const res = await fetch('/api/users');
const data = await res.json();
setUsers(data);
} catch (error) {
setError(error.message);
} finally {
setLoading(false);
}
}
Key points:
- async functions always return a Promise
- await pauses execution until Promise resolves
- Always use try-catch for error handling
- finally block runs regardless of success/failure
Q5: What is the difference between shallow copy and deep copy? How do you create them?
Shallow Copy: Copies top-level properties only. Nested objects/arrays are still referenced.
// Spread operator (shallow)
const copy = { ...original };
const arrCopy = [...originalArr];
// Object.assign (shallow)
const copy = Object.assign({}, original);
Deep Copy: Creates completely independent copy with all nested levels.
// JSON method (limitations: no functions, dates, undefined) const deepCopy = JSON.parse(JSON.stringify(original)); // structuredClone (modern, best) const deepCopy = structuredClone(original); // Lodash library const deepCopy = _.cloneDeep(original);
React State Management:
- Never mutate state directly
- Use spread for shallow updates: setState({...state, name: 'New'})
- For nested updates, create new objects at each level
Q6: Explain debouncing vs throttling with real-world React use cases.
Debouncing: Delays function execution until after a specified time has passed since the last call.
Use cases: Search bars, auto-save, window resize
// Search implementation
const searchAPI = debounce((query) => {
fetch(`/api/search?q=${query}`)
.then(res => res.json())
.then(setResults);
}, 500);
// In component
<input onChange={(e) => searchAPI(e.target.value)} />
Throttling: Ensures function executes at most once in a specified time period.
Use cases: Scroll events, button clicks, window resize with live updates
// Infinite scroll
const handleScroll = throttle(() => {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight) {
loadMoreData();
}
}, 1000);
window.addEventListener('scroll', handleScroll);
Key Difference:
- Debounce: Wait until user stops (delay after last event)
- Throttle: Execute at regular intervals (ignore intermediate events)
Q7: Explain optional chaining (?.) and nullish coalescing (??). Why are they better than older alternatives?
Optional Chaining (?.): Safely access nested properties without checking each level
// Old way - verbose const city = user && user.address && user.address.city; // New way - concise const city = user?.address?.city; // Works with methods user?.getName?.(); // Works with arrays users?.[0]?.name;
Nullish Coalescing (??): Returns right operand only when left is null/undefined
// || problem: treats 0, '', false as falsy
const count = 0;
const value1 = count || 10; // 10 (wrong!)
const value2 = count ?? 10; // 0 (correct!)
// React example
function Component({ timeout = 0 }) {
// timeout can be 0 (valid), but || would fail
const delay = timeout ?? 1000;
}
Why better:
- Shorter, more readable code
- No runtime errors for undefined access
- ?? only checks null/undefined, not all falsy values
- Prevents bugs with 0, '', false values