Low fire danger web development
Low Fire Danger develops web applications for businesses and startups. We design, engineer and develop user experiences to make your web application a pleasure to use.
We will also help you with your business and strategise your online presence. Giving you advice and guiding you through every step, from conception to execution. Lets talk: contact@lowfiredanger.com.au

Closures in Javascript

To understand closures, you should first understand that functions in javascript can be used as variables as below.

Functions as variables

Within the Javascript language, functions are treated as variables. This means that you can pass functions around like variables. which lets you doing something like this:

1
2
3
4
5
6
7
8
9
10
11
12
function createUselessFunction(value){
  return function(){
      alert(value);
  };
}

var newFunction = createUselessFunction('cat');

newFunction(); //Alerts 'cat'

//Alternative syntax
createUselessFunction('dog')(); //Alerts 'dog'

Closures

Closures are basicly functions that enclose variables. Here is an example.

1
2
3
4
5
6
7
8
9
function anotherUselessFunction(value){
  var localVariable = "I am local";
  
  return function(){
      alert(value + ' ' + localVariable);
  }
}

var uselessFunction = anotherUselessFunction('WOW!');

What happens when we execute uselessFunction()? Would localVariable be accessible from function returned by uselessFunction()? It turns out that it is accessible.

uselessFunction(); //Alerts 'WOW! I am Local'

So we see that javascript “closes” in local variables and allows returned functions to access these variables. An example use for this behaviour is described below. This example shows how we can create a custom multiplier.

1
2
3
4
5
6
7
8
9
10
11
12
function multiplier(amount){
  return function(number){
      alert(amount * number);
  };
}

var timesFive = multiplier(5);

// 5 x 3
timesFive(3); //Alerts 15
// 5 x 12
timesFive(12); //Alerts 60

Notice how 5 gets stored inside the timesFive function and we can reuse the timesFive variable as a function multiple times?

Javascript is whacky and fun!