💾 Archived View for gemini.robrohan.com › 2014-02-13-closures-in-javascript.md captured on 2022-06-03 at 23:02:37. Gemini links have been rewritten to link to archived content

View Raw

More Information

⬅️ Previous capture (2022-04-28)

-=-=-=-=-=-=-

---

author: rob

date: 2014-02-13 00:00:00+00:00

slug: closures-in-javascript

title: What are closures in javascript

---

In my pursuit of gainful employment, I was asked an interview question about closures in javascript. The question kind of threw me for a loop because when writing javascript I have never consciously thought "ok, now I need to use a closure here." I answered the question poorly - mostly just passing on it - and decided to research it later.

Now, I have used closures in Groovy which look something like this:

{{< highlight groovy >}}

def printSum = { a, b -> print a+b }

{{< /highlight >}}

They are a common occurrence in Groovy code so I know how to use them, and I know when they are useful, but within the context of javascript, I thought it was something new I had not heard about.

If you've had a similar experience, and you've used javascript for a while, let me relieve your worried mind - you already know closures in javascript, and you likely use them all the time. It's just a term that people are starting to use for a construct that has existed for quite a while.

Using the term 'closure' within javascript seems to be new, and it seems to have started because of the influx of people new to javascript, or who are coming at javascript from the perspective of another language. Anyway, the term looks as though it is here to stay, so it's good to know what it looks like.

So this is more to explain to people who know javascript what other people mean when they ask you about closures. I am going to start small, and just build all the way up.

To make sure we have a common base, lets talk about this console session:

![Javascript console output](/images/closure1.png)

First, we create a function, _f_, that logs output to the console when you call it.

Next, we assign the variable _yadda_ to the function _f_. Now this is part of where the confusion sets in. In a lot of languages (C, Java, etc) you can not just attach a variable to a simple function.

Then we add another function to that function that accesses the variable we set on the first function (_yo dog I hear you like functions_).

When we run the function attached to the first function, you can see (by the output of 'Here is a var on a function') that we can access the variable. And then just to prove it, we change the variable and output it again.

If you've done javascript for a while, all that makes perfect sense.

Now, let's build up to what people are now calling closures.

(All these examples are included in the page if you want to try them in the console)

A simple function:

{{< highlight javascript >}}

var example1 = function(a) {

return ++a;

}

{{< /highlight >}}

Running `example1(5)` yields `6` - as you would, hopefully, expect.

{{< highlight javascript >}}

var example2 = function(a) {

var b = 120;

return b + a;

}

{{< /highlight >}}

Here we're adding in a local variable _b_, and running `example2(5)` yields `125`. So what happens when we return another function instead of just a value?

{{< highlight javascript >}}

var example3 = function() {

var b = 120;

return function(a) {

b += a;

return [b, a];

}

}

{{< /highlight >}}

Running `example3()` will return the function definition of the inner function. Calling both, for example `example3()(5)`, will yield `[125, 5]`.

Before we go on, I want to point out that a lot of people already build objects this way. I don't like doing it this way for memory reasons, but something like this should look old hat to you:

{{< highlight javascript >}}

var my_obj = function() {

var a = 120; // private variable

this.b = 240; // public variable

this.method1 = function() { console.log(this.b + a); } //public method

this.method2 = function() { console.log(a); }

}

var obj = new my_obj();

obj.method1();

//->360

{{< /highlight >}}

Back to the closure example.

Since we know running the _example3_ function will return a new function, we can assign it to a variable and use it over and over:

{{< highlight javascript >}}

var c = example3();

c(5);

{{< /highlight >}}

Basically it's an 'object' (maybe class is a better way to think about it) with one unnamed method. If you noticed I've made _example3_ have one private variable that hopefully highlights the variable scope involved. If you run this over and over you'll get:

{{< highlight javascript >}}

var c = example3();

c(5);

//-> [125, 5]

c(5);

//-> [130, 5]

c(5);

//-> [135, 5]

{{< /highlight >}}

What's the difference between a object and a closure? The return of a single anonymous function, and the lack of a 'new' call pretty much. Functions return functions all the time - it's the [function of a function](http://youtu.be/RPoBE-E8VOc?t=18s). I went a little overboard there.

For example:

{{< highlight javascript >}}

typeof example4

//-> function

typeof my_obj

//-> function

typeof new example4()

//-> object

typeof new my_obj()

//-> object

{{< /highlight >}}

You can see how you can move around functions below. I am not even sure what you'd call the following. I've always called them _break off functions_.

{{< highlight javascript >}}

var my_obj= function() {

var a = 120

this.b = 240;

this.method1 = function() { console.log(this.b + a); }

this.method2 = function() { console.log(a); }

}

var obj = new my_obj();

var c = obj.method2;

c();

//->120

{{< /highlight >}}

Where this _can_ look a little odd is when function short hand is used. For example:

{{< highlight javascript >}}

var example4 = (function() {

var b = 120;

return function(a) {

b += a;

return [b, a];

}

})();

example4(5);

//-> [125, 5]

example4(10);

//-> [135, 10]

example4(5);

//-> [140, 5]

{{< /highlight >}}

However, this is doing the same thing as _example3_, but just running the anonymous function straight away instead of assigning it to an intermediate variable.

For completeness, here is the same technique as _example3_ and _example4_, but passing in a value for the inner variable:

{{< highlight javascript >}}

var example5 = (function(c) {

var b = c;

return function(a) {

b += a;

return [b, a];

}

})(10);

example5(5);

//-> [15, 5]

example5(10);

//-> [25, 10]

example5(5);

//-> [30, 5]

{{< /highlight >}}

Hopefully this saves someone some confusion when they are asked if they know javascript closures.

<script type="text/javascript">

var example1 = function(a) {

return ++a;

}

var example2 = function(a) {

var b = 120;

return b + a;

}

var example3 = function() {

var b = 120;

return function(a) {

b += a;

return [b, a];

}

}

var example4 = (function() {

var b = 120;

return function(a) {

b += a;

return [b, a];

}

})();

var example5 = (function(c) {

var b = c;

return function(a) {

b += a;

return [b, a];

}

})(10);

var my_obj= function() {

var a = 120

this.b = 240;

this.method1 = function() { console.log(this.b + a); }

this.method2 = function() { console.log(a); }

}

window.onload = function() {

console.log('Howdy do.')

}

</script>