DEV Community

Pranav Bakare
Pranav Bakare

Posted on

Advanced JavaScript concepts that every Javascript devloper should know!

Certainly! Let’s dive deeper into each topic with thorough explanations and more examples.

  1. Execution Context and Call Stack

  2. this Keyword

  3. Closures

  4. Higher-Order Functions and Callbacks

  5. Promises and async/await

  6. Event Loop and Asynchronous JavaScript

  7. Functional Programming Concepts

  8. Destructuring and Spread/Rest Operators

  9. Modules (import/export)

  10. Object-Oriented Programming in JavaScript

  11. Prototype and Prototypal Inheritance

  12. Web APIs (DOM, Fetch, LocalStorage, etc.)

  13. Error Handling (try/catch)

  14. Debouncing and Throttling

  15. Event Delegation

  16. Regular Expressions

  17. Generators and Iterators

  18. JavaScript Design Patterns

  19. Memory Management and Garbage Collection

  20. Webpack/Bundlers Concepts


  1. 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:

  1. When a function is invoked, it is added to the top of the call stack.

  2. 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


  1. 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


  1. 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


  1. this Keyword

this refers to the object that is currently executing the function.

Key Points:

  1. In global scope, this refers to the global object (e.g., window in browsers).

  2. In methods, this refers to the object that owns the method.

  3. 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


  1. Event Loop and Asynchronous JavaScript

The event loop ensures non-blocking execution in JavaScript.

How it works:

  1. Synchronous code runs on the call stack.

  2. 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


  1. 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


  1. 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


  1. 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);
}


  1. 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]


  1. 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]


  1. 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]


  1. 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.


  1. 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});
}
});


  1. 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));


  1. 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);
};
}


  1. Regular Expressions

Regex helps in pattern matching.

Example:

const regex = /\d+/;
console.log(regex.test("abc123")); // true


  1. JavaScript Design Patterns

Reusable solutions like Singleton or Observer.

Example:

const Singleton = (function () {
let instance;
return {
getInstance: () => instance || (instance = {}),
};
})();


  1. Memory Management

Garbage collection cleans unused memory.

Example:

let obj = { key: "value" };
obj = null; // Memory released


  1. 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


  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)