JavaScript: What are Closures?

So maybe you’ve heard of JavaScript closures before but you’re wondering, what exactly are they? Well, when it comes to JavaScript, you can have variables that belong to a local (a variable declared within a specific function) or global scope (variables that are accessible from anywhere in the code). You can make variables private by using closures.

Take a look at the following example:

var countUp = (function () {
var count = 0;
return function () {return count += 1;}
})();

countUp();

Now, let’s break it down:

  • The variable countUp is assigned the value of a self-invoking function.
  • It sets the count to 0 and returns a value that adds 1 to the current count.
  • It has access to the count in the parent scope.
  • The variable count is protected by the scope of the anonymous function, and can only be changed using the countUp function.

Leave a Reply