# Detailed Guide: Closures, Higher-Order Functions, Error Handling, Asynchronous JavaScript, Modules, Event
Handling, and JSON
## 1. **Closures**
Closures occur when a function "remembers" its lexical scope even after the outer function has finished executing.
### **Explanation**
- A closure is created when an inner function accesses variables from its outer function.
- It helps in creating private variables, maintaining state, and avoiding global variables.
### **Example 1: Private Counter**
```javascript
function createCounter() {
let count = 0; // Private variable
return function () {
count++;
return count;
};
const counter = createCounter();
console.log(counter()); // Output: 1
console.log(counter()); // Output: 2
```
### **Example 2: Delayed Greeting**
```javascript
function greet(name) {
return function () {
console.log(`Hello, ${name}!`);
};
const sayHi = greet("Abhi");
sayHi(); // Output: Hello, Abhi!
```
### **Daily Life Scenario**
- **Timer App:** A timer that starts, stops, and resets can use closures to maintain the time state.
### **Questions (50)**
1. What is a closure?
2. How can closures help avoid global variables? (Hint: Encapsulation)
3. Create a function that tracks how many times a button is clicked.
4. Explain how closures work in the context of event listeners.
...
---
## 2. **Higher-Order Functions**
Functions that take other functions as arguments or return functions are called higher-order functions.
### **Explanation**
- Common higher-order functions include `map()`, `filter()`, `reduce()`, and `sort()`.
- They simplify array manipulation.
### **Example 1: Using `map()` to Double Values**
```javascript
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6]
```
### **Example 2: Filtering Adults**
```javascript
const people = [
{ name: "John", age: 17 },
{ name: "Jane", age: 22 },
];
const adults = people.filter(person => person.age >= 18);
console.log(adults); // Output: [{ name: "Jane", age: 22 }]
```
### **Daily Life Scenario**
- **Shopping Cart:** Use `reduce()` to calculate the total price of items in a cart.
### **Questions (50)**
1. What is a higher-order function?
2. Use `filter()` to find even numbers in an array.
3. Write a `reduce()` function to calculate the sum of an array.
4. How does `sort()` work? (Hint: Comparator function)
...
---
## 3. **Error Handling**
### **Explanation**
Error handling ensures your code can recover gracefully from unexpected issues.
- **try-catch-finally:** Handle exceptions without crashing the program.
- **Custom Errors:** Define specific error types.
### **Example 1: Simple Try-Catch**
```javascript
try {
let result = 10 / 0;
console.log(result);
} catch (error) {
console.log("Error occurred:", error.message);
```
### **Example 2: Throwing Custom Errors**
```javascript
function checkAge(age) {
if (age < 18) {
throw new Error("Age must be 18 or above.");
return "Access granted.";
try {
console.log(checkAge(16));
} catch (error) {
console.log(error.message); // Output: Age must be 18 or above.
```
### **Daily Life Scenario**
- **Login System:** Handle errors like "Invalid password" or "User not found."
### **Questions (50)**
1. What is the purpose of `try-catch`?
2. How do you throw a custom error? (Hint: `throw new Error()`)
3. Write a function that throws an error if a number is negative.
4. What is the role of `finally` in error handling?
...
---
## 4. **Asynchronous JavaScript**
### **Explanation**
Asynchronous code allows tasks to run without blocking the main thread.
- **Callbacks:** Functions passed as arguments.
- **Promises:** Handle asynchronous operations with `.then()` and `.catch()`.
- **Async/Await:** Simplify promise handling.
### **Example 1: Callback Function**
```javascript
function fetchData(callback) {
setTimeout(() => {
callback("Data fetched");
}, 1000);
fetchData(data => console.log(data));
```
### **Example 2: Using Promises**
```javascript
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => resolve("Data fetched"), 1000);
});
fetchData.then(data => console.log(data));
```
### **Daily Life Scenario**
- **Weather App:** Fetch weather data from an API asynchronously.
### **Questions (50)**
1. What is the difference between synchronous and asynchronous code?
2. Write a promise that resolves after 2 seconds.
3. Explain how `async/await` simplifies promises.
4. What is the event loop? (Hint: Task queue and microtasks)
...
---
## 5. **Modules**
### **Explanation**
Modules allow code to be split into reusable, maintainable chunks.
- **Import/Export:** Share code between files.
- **Default vs Named Exports:** One default export per file, multiple named exports allowed.
### **Example 1: Exporting and Importing**
**math.js**
```javascript
export const add = (a, b) => a + b;
export default (a, b) => a * b;
```
**app.js**
```javascript
import multiply, { add } from "./math.js";
console.log(add(2, 3)); // Output: 5
console.log(multiply(2, 3)); // Output: 6
```
### **Daily Life Scenario**
- **E-commerce App:** Separate modules for cart, products, and user authentication.
### **Questions (50)**
1. What is the difference between default and named exports?
2. How do you import a module? (Hint: `import` keyword)
3. Write a module for user authentication.
4. Why use modules in JavaScript?
...
---
## 6. **Event Handling**
### **Explanation**
Event handling allows interaction with the DOM through events like clicks, hovers, and keypresses.
- **Bubbling and Capturing:** Events propagate up or down the DOM tree.
- **Delegation:** Handle events efficiently by listening on a parent element.
### **Example 1: Event Listener**
```javascript
document.querySelector("button").addEventListener("click", () => {
alert("Button clicked!");
});
```
### **Example 2: Event Delegation**
```javascript
document.querySelector("ul").addEventListener("click", (event) => {
if (event.target.tagName === "LI") {
alert(`You clicked on ${event.target.textContent}`);
});
```
### **Daily Life Scenario**
- **Form Validation:** Validate inputs when users interact with form fields.
### **Questions (50)**
1. What is event bubbling? (Hint: Upward propagation)
2. Write a click event listener for a button.
3. How does event delegation improve performance?
4. What is `preventDefault()` used for?
...
---
## 7. **JSON**
### **Explanation**
JSON (JavaScript Object Notation) is a lightweight data format for storing and exchanging data.
- **Parsing:** Convert JSON strings to objects.
- **Stringifying:** Convert objects to JSON strings.
### **Example 1: Parsing JSON**
```javascript
const jsonData = '{ "name": "Abhi", "age": 20 }';
const obj = JSON.parse(jsonData);
console.log(obj.name); // Output: Abhi
```
### **Example 2: Stringifying an Object**
```javascript
const obj = { name: "Abhi", age: 20 };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // Output: {"name":"Abhi","age":20}
```
### **Daily Life Scenario**
- **APIs:** Fetch and send data in JSON format.
### **Questions (50)**
1. What is JSON used for?
2. Write a JSON object for a product with name and price.
3. How do you parse a JSON string? (Hint: `JSON.parse()`)
4. What are the limitations of JSON? (Hint: No functions)
...
---
Let me know which section you'd like me to expand further or if you need the complete cheat sheet for all sections!
# Comprehensive Guide: Closures, Higher-Order Functions, Error Handling, Asynchronous JavaScript, Modules, Event
Handling, and JSON
## 1. **Closures**
Closures occur when a function "remembers" its lexical scope even after the outer function has finished executing.
### **Explanation**
- A closure is created when an inner function accesses variables from its outer function.
- It helps in creating private variables, maintaining state, and avoiding global variables.
- **Key Point:** Closures "trap" variables from their surrounding scope, keeping them alive.
### **Daily Life Scenarios**
1. **Timer App:** Maintain the state of a timer.
2. **Form Validation:** Store and validate user input step-by-step.
3. **Event Handlers:** Remember values between event triggers.
### **Examples**
#### **Example 1: Private Counter**
```javascript
function createCounter() {
let count = 0; // Private variable
return function () {
count++;
return count;
};
const counter = createCounter();
console.log(counter()); // Output: 1
console.log(counter()); // Output: 2
```
#### **Example 2: Delayed Greeting**
```javascript
function greet(name) {
return function () {
console.log(`Hello, ${name}!`);
};
const sayHi = greet("Abhi");
sayHi(); // Output: Hello, Abhi!
```
#### **Example 3: Button Click Tracker**
```javascript
function trackClicks() {
let clickCount = 0;
return function () {
clickCount++;
console.log(`Button clicked ${clickCount} times.`);
};
const buttonTracker = trackClicks();
buttonTracker(); // Output: Button clicked 1 times.
buttonTracker(); // Output: Button clicked 2 times.
```
### **Practice Questions (50)**
#### **Easy**
1. What is a closure? Write a simple example.
2. Create a closure to keep track of how many times a function is called.
3. Explain how closures help in encapsulation. (Hint: Private variables)
4. Write a function that returns another function to multiply a number by a fixed value.
5. How do closures retain access to variables even after the outer function exits?
#### **Intermediate**
6. Create a function that generates unique IDs using closures.
7. Implement a counter with increment, decrement, and reset functionality using closures.
8. Write a function that logs a sequence of numbers with a delay between each (Hint: Closures + `setTimeout`).
9. Use closures to create a "once" function that runs a callback only once.
10. Explain why closures can lead to memory leaks if not handled properly.
#### **Advanced**
11. Build a basic stopwatch with start, stop, and reset features using closures.
12. Create a closure-based cache for storing and retrieving API responses.
13. Implement a debounced function using closures.
14. Write a function that creates an array of functions, where each function logs its index (Hint: Closures + Loops).
15. What are the performance implications of closures in long-running applications?
---
## 2. **Higher-Order Functions**
Higher-order functions are functions that take other functions as arguments or return functions.
### **Explanation**
- Simplifies array manipulation and event handling.
- Enables reusable, modular code.
### **Daily Life Scenarios**
1. **E-commerce:** Use `filter()` to find items on sale.
2. **Analytics:** Use `reduce()` to calculate total website visits.
3. **Sorting:** Use `sort()` to rank products by rating.
### **Examples**
#### **Example 1: Using `map()` to Double Values**
```javascript
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // Output: [2, 4, 6]
```
#### **Example 2: Filtering Adults**
```javascript
const people = [
{ name: "John", age: 17 },
{ name: "Jane", age: 22 },
];
const adults = people.filter(person => person.age >= 18);
console.log(adults); // Output: [{ name: "Jane", age: 22 }]
```
#### **Example 3: Summing Values with `reduce()`**
```javascript
const prices = [10, 20, 30];
const total = prices.reduce((sum, price) => sum + price, 0);
console.log(total); // Output: 60
```
### **Practice Questions (50)**
#### **Easy**
1. What is a higher-order function? Give an example.
2. Write a `map()` function to add 5 to each number in an array.
3. Use `filter()` to find odd numbers in an array.
4. Explain the difference between `map()` and `forEach()`.
5. Write a `reduce()` function to find the maximum number in an array.
#### **Intermediate**
6. Use `sort()` to arrange names alphabetically.
7. Write a `filter()` function to find students who passed a test.
8. Implement a function that calculates the factorial of a number using recursion and higher-order functions.
9. Create a function that takes another function and an array, applying the function to each element.
10. Use `reduce()` to flatten a nested array.
#### **Advanced**
11. Write a function that uses `map()` and `filter()` to return names of adults from an array of people objects.
12. Implement a `compose()` function to combine multiple functions into one.
13. Create a custom `forEach()` function.
14. Use higher-order functions to generate a multiplication table.
15. Implement a throttling function using higher-order concepts.
---
## 3. **Error Handling**
Error handling ensures your code can recover gracefully from unexpected issues.
### **Explanation**
- **try-catch-finally:** Handle exceptions without crashing the program.
- **Custom Errors:** Define specific error types for better debugging.
- **Best Practices:** Always provide meaningful error messages.
### **Daily Life Scenarios**
1. **Login System:** Handle errors like "Invalid password" or "User not found."
2. **API Calls:** Retry failed network requests.
3. **File Uploads:** Catch errors like "File size too large."
### **Examples**
#### **Example 1: Simple Try-Catch**
```javascript
try {
let result = 10 / 0;
console.log(result);
} catch (error) {
console.log("Error occurred:", error.message);
```
#### **Example 2: Throwing Custom Errors**
```javascript
function checkAge(age) {
if (age < 18) {
throw new Error("Age must be 18 or above.");
return "Access granted.";
try {
console.log(checkAge(16));
} catch (error) {
console.log(error.message); // Output: Age must be 18 or above.
```
#### **Example 3: Finally Block**
```javascript
try {
console.log("Try block executed");
} catch (error) {
console.log("Catch block executed");
} finally {
console.log("Finally block executed");
```
### **Practice Questions (50)**
#### **Easy**
1. What is the purpose of `try-catch`?
2. Write a function that catches a division by zero error.
3. How do you throw a custom error? (Hint: `throw new Error()`)
4. What is the role of `finally` in error handling?
5. Explain the difference between syntax errors and runtime errors.
#### **Intermediate**
6. Write a function that retries an API call up to 3 times in case of failure.
7. Implement a function that validates user input and throws errors for invalid data.
8. Create a custom error class for handling validation errors.
9. Use `try-catch` to handle JSON parsing errors.
10. Write a program to simulate file reading and handle file-not-found errors.
#### **Advanced**
11. Create an error-handling middleware for a Node.js application.
12. Implement a function to log errors to an external service.
13. Write a function that handles multiple types of errors (e.g., TypeError, ReferenceError).
14. Build a circuit breaker mechanism using error handling.
15. How can error handling be combined with promises or async/await?
---
## 4. **Asynchronous JavaScript**
Asynchronous JavaScript allows you to perform tasks without blocking the main thread.
### **Explanation**
- **Callbacks:** Functions passed as arguments to execute later.
- **Promises:** Handle asynchronous operations with `.then()` and `.catch()`.
- **Async/Await:** Cleaner syntax for promises.
### **Daily Life Scenarios**
1. **API Requests:** Fetching data from servers.
2. **Animations:** Sequential animations on a webpage.
3. **Timers:** Delayed actions like notifications.
### **Examples**
#### **Example 1: Callback Function**
```javascript
function fetchData(callback) {
setTimeout(() => {
callback("Data fetched!");
}, 1000);
fetchData(message => console.log(message)); // Output: Data fetched!
```
#### **Example 2: Promises**
```javascript
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data fetched!");
}, 1000);
});
fetchData.then(data => console.log(data)); // Output: Data fetched!
```
#### **Example 3: Async/Await**
```javascript
async function fetchData() {
const data = await new Promise(resolve => setTimeout(() => resolve("Data fetched!"), 1000));
console.log(data);
fetchData(); // Output: Data fetched!
```
### **Practice Questions (50)**
#### **Easy**
1. What is a callback function? Write an example.
2. Explain the difference between synchronous and asynchronous code.
3. Write a promise that resolves after 2 seconds.
4. What is the purpose of `async` and `await`?
5. Explain the states of a promise.
#### **Intermediate**
6. Write a function that fetches data from an API using promises.
7. Create a function that retries a failed API call using promises.
8. Write a program that chains multiple promises.
9. Use `async/await` to fetch and log data from an API.
10. Implement a delay function using promises.
#### **Advanced**
11. Build a function to handle both resolved and rejected promises.
12. Write a custom implementation of a promise.
13. Implement a function that executes multiple promises in parallel.
14. Use `async/await` with error handling to log errors gracefully.
15. Explain the difference between microtasks and macrotasks in the event loop.
---
(Additional sections for **Modules**, **Event Handling**,