Coding Schools


 
Python | C Sharp | Azure AI | HTML | JavaScript | CSS | SQL Server
JavaScript - Basic Structure
Closures in JavaScript
Using CSS in Javascript
OOPS in Javascript
Popup Window in Javascript
Printout a page in Javascript
Variable declaration in JavaScript
Difference of let, var and const
JavaScript - JSON Parse & Stringify

Closures in JavaScript



A closure in JavaScript is a powerful feature where a function remembers and accesses variables from its outer scope even after that outer function has finished executing. In other words, a closure allows a function to "enclose" or capture its lexical scope.

Key Concepts of Closures

  1. Lexical Scoping: Inside a nested function, JavaScript has access to variables defined in the outer (or parent) function. This scope chain continues upwards to the global scope.

  2. Retention of Scope: The inner function retains access to the outer function' variables even after the outer function has returned.

Why Use Closures?

  • Encapsulation: Closures can be used to create private variables and functions.

  • Function Factories: Closures allow functions to be created dynamically with specific environments.

  • Callbacks and Event Handlers: Closures maintain state in asynchronous operations like callbacks and event handlers.

Example of a Closure

Here' a simple example demonstrating how closures work:

javascript
function createCounter() {
    // Local variable 'count' inside the outer function
    let count = 0;

    // Returning an inner function (a closure)
    return function() {
        count++; // Accessing and modifying the outer function's variable
        console.log(count);
    };
}

const counter = createCounter(); // 'counter' now holds the inner function
counter(); // Output: 1
counter(); // Output: 2
counter(); // Output: 3

Explanation

  • The createCounter function defines a local variable count.

  • It returns an inner function that increments count and logs the current count.

  • Even after createCounter finishes executing, the returned function (assigned to counter) maintains access to count.

Another Example: Private Scope

javascript
function createSecretHolder(secret) {
    return {
        getSecret: function() {
            return secret;
        },
        setSecret: function(newSecret) {
            secret = newSecret;
        }
    };
}

const mySecret = createSecretHolder("shh... it's a secret!");
console.log(mySecret.getSecret()); // Output: "shh... it's a secret!"
mySecret.setSecret("new secret");
console.log(mySecret.getSecret()); // Output: "new secret"

Explanation

  • The createSecretHolder function creates an object with methods to get and set a secret value.

  • The secret variable remains private within the closure scope, providing controlled access through getSecret and setSecret methods.

Closures can sometimes be a bit tricky to understand at first, but they are extremely useful once you get the hang of them. Would you like to see more examples or delve into other related concepts?




All rights reserved | Privacy Policy | Sitemap