What are Closures in JavaScript?

What are Closures in JavaScript?

Ferenc Almasi β€’ Last updated 2020 November 01 β€’ Read time 2 min read
  • twitter
  • facebook
JavaScript

Closure often confuse people in JavaScript. In one sentence: It is an inner function that has access to the other function's variables. It’s a combination of a function and the lexical environment in which it was declared.

A great example of closures are callbacks. Note the differences between scopes and closures in the following example:

Copied to clipboard! Playground
// Note the differences between scope and closure

// scope: global
var a = 1;

(function one() {
  // scope: one
  // closure: one, global
  
  var b = 2;

  (function two() {
    // scope: two
    // closure: two, one, global
    
    var c = 3;

    (function three() {
      // scope: three
      // closure: three, two, one, global
      
      var d = 4;
      
      // This will output 10 as we have access to outer enclosing function variables
      console.log(a + b + c + d);
    })();
  })();
})();
closure.js
  • The scope refers to the lexical environment of the function
  • While closure encompasses the lexical scope of other enclosing function as well
What are JavaScript closures?
If you would like to see more Webtips, follow @flowforfrank

50 JavaScript Interview Questions

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.