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
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

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.