Certainly! Let’s dive deeper into each topic with thorough explanations and more examples.
Execution Context and Call Stack
this Keyword
Closures
Higher-Order Functions and Callbacks
Promises and async/await
Event Loop and Asynchronous JavaScript
Functional Programming Concepts
Destructuring and Spread/Rest Operators
Modules (import/export)
Object-Oriented Programming in JavaScript
Prototype and Prototypal Inheritance
Web APIs (DOM, Fetch, LocalStorage, etc.)
Error Handling (try/catch)
Debouncing and Throttling
Event Delegation
Regular Expressions
Generators and Iterators
JavaScript Design Patterns
Memory Management and Garbage Collection
Webpack/Bundlers Concepts
- Execution Context and Call Stack
An execution context is the environment where JavaScript code runs. It determines what variables, objects, and functions are accessible. The call stack is a structure that tracks function calls.
How it works:
When a function is invoked, it is added to the top of the call stack.
When the function execution completes, it is removed from the stack.
Example:
function first() {
console.log("First");
second();
console.log("First End");
}
function second() {
console.log("Second");
}
first();
// Call Stack:
// 1. first() -> Logs "First"
// 2. second() -> Logs "Second"
// 3. first() -> Logs "First End"
// Output: First, Second, First End
- Closures
Closures allow functions to retain access to their lexical scope even after the outer function has finished executing.
Key Idea: Closures are created every time a function is defined, and they "remember" the variables in their scope.
Example:
function outerFunction(outerVariable) {
return function innerFunction(innerVariable) {
console.log(Outer: ${outerVariable}, Inner: ${innerVariable}
);
};
}
const closureFunc = outerFunction("outside");
closureFunc("inside");
// Output: Outer: outside, Inner: inside
- Prototype and Prototypal Inheritance
JavaScript uses prototypal inheritance, where objects inherit from other objects via the prototype chain.
Example:
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function () {
console.log(${this.name} makes a sound.
);
};
const dog = new Animal("Dog");
dog.speak(); // Dog makes a sound
console.log(dog.proto === Animal.prototype); // true
- this Keyword
this refers to the object that is currently executing the function.
Key Points:
In global scope, this refers to the global object (e.g., window in browsers).
In methods, this refers to the object that owns the method.
In arrow functions, this is inherited from the surrounding scope.
Examples:
const obj = {
name: "Alice",
greet() {
console.log(Hello, ${this.name}
);
},
};
obj.greet(); // Hello, Alice
const greetGlobal = obj.greet;
greetGlobal(); // Hello, undefined (in strict mode) or Hello, global
- Event Loop and Asynchronous JavaScript
The event loop ensures non-blocking execution in JavaScript.
How it works:
Synchronous code runs on the call stack.
Asynchronous tasks (like setTimeout) are added to the task queue and wait for the call stack to clear.
Example:
console.log("Start");
setTimeout(() => console.log("Timeout"), 1000);
console.log("End");
// Output: Start, End, Timeout
- Promises and async/await
Promises represent the eventual result of an asynchronous operation. async/await simplifies promise chaining.
Example:
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => resolve("Fetched Data"), 1000);
});
}
async function getData() {
const data = await fetchData();
console.log(data);
}
getData(); // Fetched Data
- Modules (import/export)
Modules allow you to split code into reusable chunks.
Example:
// math.js
export function add(a, b) {
return a + b;
}
// app.js
import { add } from './math.js';
console.log(add(3, 5)); // 8
- Error Handling (try/catch)
try/catch blocks handle errors gracefully.
Example:
try {
const result = JSON.parse("Invalid JSON");
} catch (error) {
console.log("Error occurred:", error.message);
}
- Higher-Order Functions and Callbacks
Higher-order functions take other functions as arguments or return them.
Example:
const numbers = [1, 2, 3, 4];
const squaredNumbers = numbers.map((num) => num ** 2);
console.log(squaredNumbers); // [1, 4, 9, 16]
- Functional Programming Concepts
Functional programming avoids mutating data.
Example:
const nums = [1, 2, 3];
const doubled = nums.map((n) => n * 2); // Pure function
console.log(doubled); // [2, 4, 6]
- Destructuring and Spread/Rest Operators
These operators simplify data handling.
Example:
const obj = { a: 1, b: 2 };
const { a, b } = obj; // Destructuring
console.log(a, b); // 1, 2
const nums = [1, 2, 3];
const newNums = [...nums, 4]; // Spread
console.log(newNums); // [1, 2, 3, 4]
- Object-Oriented Programming
OOP in JavaScript uses classes and prototypes.
Example:
class Car {
constructor(brand) {
this.brand = brand;
}
drive() {
console.log(${this.brand} is driving.
);
}
}
const car = new Car("Tesla");
car.drive(); // Tesla is driving.
- Event Delegation
Event delegation allows efficient event handling.
Example:
document.getElementById("list").addEventListener("click", (event) => {
if (event.target.tagName === "LI") {
console.log(Clicked on ${event.target.textContent}
);
}
});
- Web APIs
Interact with browser features like DOM and Fetch.
Example:
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then((response) => response.json())
.then((data) => console.log(data));
- Debouncing and Throttling
Control how often a function is executed.
Example:
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
- Regular Expressions
Regex helps in pattern matching.
Example:
const regex = /\d+/;
console.log(regex.test("abc123")); // true
- JavaScript Design Patterns
Reusable solutions like Singleton or Observer.
Example:
const Singleton = (function () {
let instance;
return {
getInstance: () => instance || (instance = {}),
};
})();
- Memory Management
Garbage collection cleans unused memory.
Example:
let obj = { key: "value" };
obj = null; // Memory released
- Generators and Iterators
Generators allow pausing and resuming function execution.
Example:
function* numbers() {
yield 1;
yield 2;
yield 3;
}
const gen = numbers();
console.log(gen.next().value); // 1
- Webpack/Bundlers
Bundle JavaScript files for production.
Example:
// webpack.config.js
module.exports = {
entry: "./src/index.js",
output: { filename: "bundle.js" },
};
These detailed explanations and examples will give you a solid understanding of advanced JavaScript concepts!
Top comments (0)