Technical Challenge: Understanding JavaScript Closures

I’m going to try something new and start posting technical challenges for us to unpack.  When going after web developer jobs, you may be asked to complete a technical interview that could involve white board exercises.  It’s better to be prepared, so as I go through sample technical challenges, I’ll post about them and what I’ve learned.

My technical challenge for the weekend focused on closures in JavaScript.  Take the following question:

Q: What is a closure and how can it be useful?

Let me start off by explaining scope, local, and global variables in JavaScript briefly.

With scope, we define variables as either global or local.  Global variables are those defined outside of functions, where as local variables are defined within them.  Unlike global variables, local variables cannot be accessed outside the function that created it.  I’ve created an example below in which I define both a global and local variable as msg that is assigned two different strings to illustrate scope.

var msg = "Our Code Blog";
function Show() {
    var msg = "Hello World !";
    console.log("Value of 'msg' inside the function " + msg);
}
console.log("Value of 'msg' outside the function : " + msg);

Even though msg was assigned the string “Hello World!” locally in the function Show(), the scope when called outside that function is global, therefore the string assigned to the global variable msg is logged.

So why the short lesson on scope? Well, think of a first class function as a global variable, and inner functions as a local variable.

In JavaScript, a first class function is a function that can be (1) assigned to variables, (2) passed as arguments and returned by other functions, or (3) included in another data structure.  Closures are created by defining an inner function inside a first class one.  Unlike a local variable, an inner function can be accessed from outside the first class function that created it using a closed over variable, or closure.  That’s what makes closures significant.

When studying closures, I found this article by Colin Ihrig gives a great breakdown.  I used one of his examples of how closures are created in my 2nd example with some slight changes for better understanding.

In the example, I defined a first class function (in this case, an object) called Car that takes a parameter of model. Within the object Car, I declared a variable _model and assigned it to the parameter model.  Also within the object Car, I created an inner function that returns _model, using the value this to point to the inheriting object.  I’ll call .getModel( ) later in the script.

function Car(model) {
    var _model = model;
    this.getModel = function() {
      return _model;
    };
 }

Adding on to the example, I declared a global variable lowercase car and assigned it a new Car with the parameter mustang as the model.  After that, I’ll use _model to change it to something different. Then I’ll assign the getModel( ) function to car to see what it logs.

function Car(model) {
    var _model = model;
    this.getModel = function() {
      return _model;
    };
 }
var car = new Car("mustang");
car._model = "ranger";

var my_car = car.getModel();
console.log(my_car);

Even though I assigned the model for car as ranger, when I called getModel( ) on car as assigned to the given variable, mustang is returned.  The variable _model is closed over and bound to whatever parameter you originally pass through it, in this case mustang.  This is one way how closures can be useful: emulating private data, in which variables are only accessed and disclosed of through the closure function.

In answering the technical question: what is a closure and how can it be useful? I offer the following answer:

A closure is an object in JavaScript that is created when an inner function is accessible from outside the function that created it. It’s independent, and can be useful in simulating privacy as a design pattern.

In the scenario that you are asked this question in a technical interview, you could give this definition and use the above example as a white board answer.  If you are looking for similar (and more simple) examples, see Mozilla Developer docs on closures.

Hope this helps! Comment below if there are other technical challenges that you want me to unpack in a future post in prepping for web developer interviews. Have you gone through a technical interview recently? What questions have you been asked and how you have solved them?

Advertisements