Last Updated: February 25, 2016
·
1.358K
· ericraio

Learn JavaScript / CoffeeScript Closures

So for this week I wanted to write about JavaScript closures then show you how you can write it in CoffeeScript.

function makeCounter() {
  var x = 0;

  function incrementCounter() {
    x++;
    return x;
  };

  return incrementCounter;
};

var y = makeCounter(); //=> function incrementCounter() {
                   //      x++;
                   //      return x;
                   //   }
y(); //=> 1
y(); //=> 2
y(); //=> 3

In CoffeeScript this function can be written like this

makeCounter = () ->
  x = 0
  incrementCounter = () ->
    x++
    return x
  return incrementCounter

y = makeCounter()
y() #=> 1
y() #=> 2
y() #=> 3

You can see that as you call makeCounter and assign it to a variable(in this example it is y); you are returning a function. Now when you call y, it looks like you are incrementing a private variable but that is not the case. JavaScript has a feature apart of the language called Lexical Scoping. With our function makeCounter, it defines a variable and defines an inner function called incrementCounter. Our incrementCounter function is aware of all variables defined within makeCounter because of Lexical Scoping. Even if we return incrementCounter from makeCounter, when incrementCounter is called, we still have a reference to what makeCounter has defined. Writing your code this way is called a closure.

Closures can be great when dealing with variables that you want to change every time you run the same function. At sony we use them for our language translations, When the language changes, the return value will return a different translated string.

Also if you wanted to build new co-ordinates for a game or if you wanted to generate a new ID for a user in an application. If you are up for it. Try writing a gist of some example closures and link the gist in the comments.

[source]
http://en.wikipedia.org/wiki/Closure_(computer_science)
http://en.wikipedia.org/wiki/Lexical_scoping#Lexical_scoping_and_dynamic_scoping

1 Response
Add your response

You does not need return keyword when use CoffeeScript, lets see:

makeCounter = () ->
  x = 0
  () -> ++x
over 1 year ago ·