DEV Community

Abdusanadzoda Abdulaziz
Abdusanadzoda Abdulaziz

Posted on • Updated on

JavaScript Closure 🎆

Hey mates on the internet (●'◡'●)

Now, it’s time to talk about closures.

What is Closure?

A closure is a function that has access to its outer function scope even after the outer function has returned. This means a closure can remember and access variables and arguments of its outer function even after the function has finished.

Before we dive into closures, let’s first understand the lexical scope.


What is a Lexical Scope?

A lexical scope or static scope in JavaScript refers to the accessibility of the variables, functions, and objects based on their physical location in the source code. For example:

let a = 'global';
  function outer() {
    let b = 'outer';
    function inner() {
      let c = 'inner'
      console.log(c);   // prints 'inner'
      console.log(b);   // prints 'outer'
      console.log(a);   // prints 'global'
    }
    console.log(a);     // prints 'global'
    console.log(b);     // prints 'outer'
    inner();
  }
outer();
console.log(a);         // prints 'global'
Enter fullscreen mode Exit fullscreen mode

Here the inner function can access the variables defined in its own scope, the outer function’s scope, and the global scope. And the outer function can access the variable defined in its own scope and the global scope.

So a scope chain of the above code would be like this:

Global {
  outer {
    inner
  }
}
Enter fullscreen mode Exit fullscreen mode

Notice that inner function is surrounded by the lexical scope of outer function which is, in turn, surrounded by the global scope. That’s why the inner function can access the variables defined in outer function and the global scope.

Quiz — Test Your Knowledge

What would the below code print out?

var name = 'John'

function greet (name) {  
  return (function () {
    console.log('Hello ' + name)
  })
}

var sayHello = greet(name)

name = 'Sam'

sayHello()
Enter fullscreen mode Exit fullscreen mode

The answer is Hello John.

Yes, even though we altered the value of name to 'Sam' before we invoked sayHello. It’s as if, the value of name was captured before it was reassigned to 'Sam'.

Yes, even though we altered the value of name to 'Sam' before we invoked sayHello. It’s as if, the value of name was captured before it was reassigned to 'Sam'.

That is exactly what happened — this is closure in action.

Top comments (0)