HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Closures

A closure is a function that has access to the outer (parent) scope, even after the outer function has finished executing. JavaScript variables can belong to the local or global scope. Closures make it possible for a function to have "private" variables.


The Global/Local Scope Review

A function can access variables defined inside the function (local scope) or outside of it (global scope).

let a = 4; // Global
function myFunction() {
  return a * a; // Can access global variable
}

The Counter Dilemma

Suppose you want to use a variable for counting something, and you want this counter to be available to all functions. But you also want to prevent any other code from changing the counter accidentally.

If the counter is global, any script can change it. If it is local, it resets every time the function is called. The solution is Closure.


JavaScript Closure Syntax

A closure is created when an inner function is made available outside of the function in which it was defined.

const add = (function () {
  let counter = 0; // "Private" variable
  return function () {
    counter += 1; 
    return counter;
  }
})();

add(); // returns 1
add(); // returns 2
add(); // returns 3

How it works:

  1. The self-invoking function runs once. It sets the counter to 0, and returns a function expression.
  2. The add variable becomes a function.
  3. The "magic" is that the add function has access to the counter in the parent scope. This is called a JavaScript closure.

Why use Closures?

  • Data Privacy: It allows you to create private variables that cannot be accessed from the outside console or other scripts.
  • Encapsulation: You can group data and the functions that manipulate that data together.
  • Modular Code: They are essential for creating modules and advanced design patterns in JavaScript.

Key Points to Remember

  • A closure gives you access to an outer function’s scope from an inner function
  • In JavaScript, closures are created every time a function is created
  • They are perfect for creating state without global variables
  • Closures "remember" the environment in which they were created
  • Essential for professional patterns like Manufacturing and Module patterns