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.

WDI Day Nine: Scopes, Closures, & User Stories

We reviewed JavaScript scope, context, and closures. It was helpful running through a couple of scope exercises, to ensure we knew when variables were being read locally or globally in different functions. Context involved going over “this,” and what “this” is referring to. I felt like I was able to grasp most of the concepts, although one of our in-class exercises proved to be pretty difficult for me. I feel like whenever something involves math, it takes me a little while to figure out how to get it working properly. Hopefully that will improve with time.

In the afternoon we went over problem solving and user stories in group. We were also told what the requirements will be for our first project which will need to be completed by Thursday of next week. I’ve decided to tackle making a JavaScript flash card game. My goal is actually to finish it early so I can tackle another game like hang man. I’m probably being a little overly ambitious, but we shall see what I can do…

Resources