4 - Advanced Concepts

Closures in Depth

What are Closures?

  • Closures: Functions that can access variables from their enclosing scope, even after that scope has exited.

  • How They Work: Closures keep references to the outer scope variables alive, allowing you to use them later.

    • Example:

      function makeMultiplier(x) {
          return function(y) {
              return x * y;
          };
      }
      const multiplyBy3 = makeMultiplier(3);
      console.log(multiplyBy3(4));  // Output: 12
      console.log(multiplyBy3(5));  // Output: 15
    • Explanation: The inner function remembers x from the outer function, even after makeMultiplier has finished executing.

Use Cases of Closures

  • Data Privacy: Create private variables by encapsulating them within a function.

    • Example:

      function Counter() {
          let count = 0;
          return {
              increment: function() {
                  count++;
                  return count;
              },
              decrement: function() {
                  count--;
                  return count;
              }
          };
      }
      const counter = Counter();
      console.log(counter.increment());  // Output: 1
      console.log(counter.decrement());  // Output: 0
  • Event Handlers: Closures are often used in event listeners to retain access to external variables.

Higher-Order Functions

What are Higher-Order Functions?

  • Higher-Order Functions: Functions that either take other functions as arguments or return functions.

    • Examples include map(), filter(), and reduce().

    • Example:

Common Higher-Order Functions

  • map(): Creates a new array by applying a function to each element of the original array.

    • Example:

  • filter(): Creates a new array with all elements that pass the test implemented by the provided function.

    • Example:

  • reduce(): Executes a reducer function on each element of the array, resulting in a single output value.

    • Example:

The this Keyword in JavaScript

Understanding this

  • this: Refers to the object that is executing the current function.

    • In the global scope, this refers to the global object (window in browsers).

    • In an object method, this refers to the object the method is called on.

    • In arrow functions, this retains the value from the enclosing lexical context.

Examples of this

  • Global Scope:

  • Object Method:

  • Arrow Function:

Prototypes and Inheritance

What is a Prototype?

  • Prototype: Every JavaScript object has a prototype, which is an object itself from which other objects inherit properties and methods.

    • Prototype Chain: Mechanism through which objects inherit from one another.

    • Example:

Inheritance

  • Inheritance: Mechanism for creating a new object based on an existing object.

    • Example using Prototypal Inheritance:

Classes in JavaScript (ES6)

  • Classes: A syntactic sugar for creating objects and dealing with inheritance in JavaScript.

    • Syntax:

The Event Loop and Asynchronous JavaScript

The Event Loop

  • Event Loop: Handles asynchronous operations by continuously checking the call stack and the task queue.

    • How It Works:

      • The call stack handles function execution.

      • The task queue (or callback queue) holds callback functions waiting to be executed.

      • Example:

Asynchronous JavaScript

  • Callbacks: Functions passed as arguments to other functions, often used to handle asynchronous code.

    • Example:

  • Promises: Objects representing a value that may be available now, or in the future, or never.

    • Example:

  • Async/Await: Syntactic sugar to work with promises in a more readable manner.

    • Example:

Summary

  • Closures: Essential for retaining access to the scope of an outer function, allowing for data privacy and function factories.

  • Higher-Order Functions: Functions like map(), filter(), and reduce() that accept or return other functions.

  • this Keyword: Understand how this behaves differently in various contexts, especially with arrow functions.

  • Prototypes and Inheritance: The fundamental mechanism for object inheritance in JavaScript.

  • Event Loop: Understand how JavaScript handles asynchronous code using the event loop.


Next Chapter: JavaScript in the Browser

Last updated