Debug School

rakesh kumar
rakesh kumar

Posted on

closure and scope chain in javascript

In JavaScript, a closure is a function that has access to variables defined in its outer lexical environment, even after the outer function has returned. The scope chain is the order in which JavaScript looks for variables when a function is executed. When a function is executed, JavaScript first looks for the variable within its local scope, and if it cannot find it, it looks up the scope chain to find the variable in the outer lexical environment.

Here's an example of a closure and scope chain in JavaScript:

function outerFunction() {
  var outerVariable = "I'm from outerFunction!";

  function innerFunction() {
    var innerVariable = "I'm from innerFunction!";
    console.log(innerVariable);
    console.log(outerVariable);
  }

  return innerFunction;
}

var innerFunc = outerFunction();
innerFunc(); // Output: "I'm from innerFunction!" and "I'm from outerFunction!"
Enter fullscreen mode Exit fullscreen mode

Image description

In the above example, the outerFunction defines a variable outerVariable and a nested function innerFunction. The innerFunction defines its own variable innerVariable and logs both innerVariable and outerVariable to the console.

When outerFunction is called and its return value is assigned to the variable innerFunc, innerFunc becomes a closure that retains access to outerVariable even after outerFunction has returned. When innerFunc is called, JavaScript looks for innerVariable within its local scope, and since it finds it, logs it to the console. It then looks for outerVariable in the outer lexical environment, finds it, and logs it to the console as well.

Image description

chris()
bob()
john()

Top comments (0)