nova / javascript.txt
crazysanthosh's picture
Upload 25 files
7fde9b9 verified
Raw History Blame Contribute Delete
8.08 kB
## JavaScript Closures
Definition: A closure is a function that remembers the variables from its outer scope even after the outer function has finished executing.
Explanation: When a function is defined inside another function, the inner function forms a closure over the outer function's variables. This is fundamental to JavaScript and enables patterns like data privacy, function factories, and the module pattern. Closures capture the variable reference, not its value.
Example: A counter function factory that maintains private state.
Code Example:
```javascript
function makeCounter(start = 0) {
let count = start; // This is "closed over"
return {
increment() { count++; },
decrement() { count--; },
getCount() { return count; }
};
}
const counter = makeCounter(10);
counter.increment();
counter.increment();
console.log(counter.getCount()); // 12
// count is private — can't access it directly
```
Best Practices: Use closures for data privacy and encapsulation. Be careful with closures in loops — use let (block-scoped) or an IIFE. Understand that closures hold references to outer variables, which can prevent garbage collection.
Common Errors: Classic loop bug with var — all closures in the loop share the same i. Accidental memory leaks from closures holding large outer scopes. Confusing closure scope with this.
Interview Questions: What is a closure and why is it useful? Explain the famous loop-closure bug with var. How does a closure differ from a regular function scope?
## JavaScript Promises and Async/Await
Definition: Promises represent eventual completion or failure of asynchronous operations. Async/await is syntactic sugar over Promises for cleaner async code.
Explanation: A Promise has three states: pending, fulfilled, or rejected. .then() handles success, .catch() handles errors, .finally() always runs. Promise.all() waits for all promises; Promise.race() resolves with the first. async functions always return a Promise. await can only be used inside async functions.
Example: Fetching user data from an API.
Code Example:
```javascript
// Promise chain
fetch('/api/user/1')
.then(res => res.json())
.then(user => console.log(user.name))
.catch(err => console.error('Failed:', err));
// Async/Await (cleaner)
async function getUser(id) {
try {
const res = await fetch(`/api/user/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const user = await res.json();
return user;
} catch (err) {
console.error('Error fetching user:', err);
throw err; // Re-throw if needed
}
}
// Parallel requests
const [user, posts] = await Promise.all([
getUser(1),
fetch('/api/posts').then(r => r.json())
]);
```
Best Practices: Always handle errors with .catch() or try/catch. Use Promise.all() for parallel independent requests. Avoid Promise.all() if one failure shouldn't cancel the others (use Promise.allSettled()).
Common Errors: Forgetting to await inside an async function. Not catching errors in promise chains. Accidentally creating promise chains that don't return, losing the chain.
Interview Questions: What is the difference between Promise.all and Promise.allSettled? Explain the event loop and microtask queue. What happens if you use await without async?
## JavaScript Event Loop
Definition: The event loop is the mechanism that allows JavaScript to perform non-blocking operations despite being single-threaded, by offloading tasks to the browser/Node APIs.
Explanation: JavaScript has a single call stack. When async tasks (setTimeout, fetch, etc.) complete, their callbacks are pushed to the task queue. The event loop checks if the call stack is empty, then processes tasks from the queue one at a time. Microtasks (Promise callbacks) have higher priority than macrotasks (setTimeout, setInterval).
Example: Understanding why setTimeout(fn, 0) doesn't execute immediately.
Code Example:
```javascript
console.log('1 - start');
setTimeout(() => console.log('2 - setTimeout'), 0);
Promise.resolve()
.then(() => console.log('3 - Promise'));
console.log('4 - end');
// Output order:
// 1 - start
// 4 - end
// 3 - Promise (microtask — runs before macrotask)
// 2 - setTimeout (macrotask)
```
Best Practices: Understand task vs microtask priority to predict execution order. Avoid blocking the event loop with heavy synchronous computation. Use Web Workers for CPU-intensive tasks.
Common Errors: Assuming setTimeout(fn, 0) runs immediately. Blocking the event loop with a long synchronous loop. Expecting microtasks and macrotasks to run in declaration order.
Interview Questions: Explain the event loop in your own words. What is the difference between a microtask and a macrotask? How does Node.js differ from browser JS execution?
## JavaScript ES6+ Features
Definition: ES6 (ECMAScript 2015) and later versions introduced major improvements to JavaScript's syntax and capabilities.
Explanation: Key ES6+ features: Arrow functions (lexical this), Destructuring (arrays & objects), Spread/rest operator (...), Template literals (``), let/const (block scoped), Default parameters, Modules (import/export), Classes, Optional chaining (?.), Nullish coalescing (??), and Array methods (map, filter, reduce, find, some, every).
Example: Modern data transformation using array methods and destructuring.
Code Example:
```javascript
const users = [
{ name: 'Alice', age: 28, role: 'admin' },
{ name: 'Bob', age: 22, role: 'user' },
{ name: 'Carol', age: 35, role: 'admin' }
];
// Destructuring + filter + map
const adminNames = users
.filter(({ role }) => role === 'admin')
.map(({ name, age }) => `${name} (${age})`);
console.log(adminNames); // ['Alice (28)', 'Carol (35)']
// Optional chaining & nullish coalescing
const user = null;
const displayName = user?.profile?.name ?? 'Anonymous';
```
Best Practices: Use const by default, let when mutation is needed, never var. Use optional chaining to safely access nested properties. Prefer destructuring over manual property access.
Common Errors: Arrow functions don't have their own this — avoid them as object methods. Using const on objects doesn't make them immutable (just the binding). Confusion between null and undefined with nullish coalescing.
Interview Questions: What is the difference between let, const, and var? How does the spread operator differ from rest parameters? Explain optional chaining and nullish coalescing.
## JavaScript Prototypes and Inheritance
Definition: JavaScript is a prototype-based language. Every object has a [[Prototype]] chain that is checked when a property isn't found on the object itself.
Explanation: Before ES6 classes, inheritance was done via prototype chains directly. Object.create() creates an object with a specific prototype. Function.prototype is where methods live. ES6 classes are syntactic sugar over prototypal inheritance — under the hood, it's the same mechanism. instanceof checks the prototype chain.
Example: All arrays share methods (map, filter) via Array.prototype.
Code Example:
```javascript
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
return `Hi, I'm ${this.name}`;
};
// ES6 class equivalent (recommended)
class Animal {
constructor(name) { this.name = name; }
speak() { return `${this.name} makes a sound.`; }
}
class Dog extends Animal {
speak() { return `${this.name} barks.`; }
}
const d = new Dog('Rex');
console.log(d.speak()); // Rex barks.
console.log(d instanceof Animal); // true
```
Best Practices: Use ES6 class syntax for clarity. Avoid modifying built-in prototypes (Array.prototype, etc). Use Object.create(null) for pure hash maps with no prototype.
Common Errors: Forgetting new when calling a constructor function (this becomes global). Adding heavy methods directly to instance (duplicates for each object). Not understanding the prototype chain causes "is not a function" errors.
Interview Questions: How does prototypal inheritance differ from classical inheritance? Explain how the new keyword works step by step. What is the prototype chain?