JS Tutorial



JS CLOSURES


JavaScript Closures 🔒

A closure is a function that remembers its lexical scope, even when the function is executed outside that scope. In simpler terms, a closure gives you access to variables from an outer function even after the outer function has finished execution.

🔼 How Closures Work

When a function is created inside another function, it forms a closure. The inner function retains access to the outer function's variables, even after the outer function has completed execution.

// Example 1: Basic Closure
function outerFunction() {
  let outerVar = 'I am outer';
  
  function innerFunction() {
    console.log(outerVar); // Accesses outer function's variable
  }
  
  return innerFunction;
}

const closureExample = outerFunction();
closureExample(); // "I am outer"

🔼 Closures and Variables

Closures help maintain state across multiple function calls, which can be very useful when you need to persist information between function executions.

// Example 2: Closures and Variables
function counter() {
  let count = 0;
  
  return function() {
    count++;
    console.log(count);
  };
}

const increment = counter();
increment(); // 1
increment(); // 2
increment(); // 3

🔼 Closures with Arguments

Closures can also capture function arguments, enabling more advanced behavior like factory functions.

// Example 3: Closures with Arguments
function multiplyBy(factor) {
  return function(num) {
    return num * factor;
  };
}

const multiplyBy2 = multiplyBy(2);
console.log(multiplyBy2(5)); // 10
console.log(multiplyBy2(3)); // 6

const multiplyBy3 = multiplyBy(3);
console.log(multiplyBy3(4)); // 12

🎮 Interactive Example

Click to see how closures maintain their environment even after the outer function has finished executing:

📘 Summary

  • Closure: A function that retains access to its lexical scope, even after the outer function has finished execution.
  • State Persistence: Closures allow functions to "remember" their environment, maintaining state between calls.
  • Use Case: Closures are often used to create private variables, factory functions, and maintain a persistent state in asynchronous programming.
Tip: Closures are powerful for encapsulating state and creating functions with persistent data without polluting the global scope.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review