Javascript closures

There are many good reasons to use a closure but I often forget it's syntax. Below are a few common use cases and examples.

Counting Numbers

This solution is really great for keeping a single score within a game or maybe a timer.

var add = (function () {
    var counter = 0;
    return function () {return counter += 1;}
})();
add(); // 1
add(); // 2

Concatenating Strings

This method will accept a name parameter, concatenate it and return a greeting.

function sayHello2(name) {
  //A. Create a message
  var text = "Hello " + name;
  //B. This function will print the message.
  var salutation = function() { console.log(text); }
  return salutation;
}
var greetPatron = sayHello2("Bob");
greetPatron(); // "Hello Bob"

Lodash

If you're looking for a Javascript library that can help you keep your code looking pretty, I really like the Lodash utility ._spread.

var data = [{ id: 1, name: "Chris"}, { id: 2, name: "Bob" }];
var newObj = { id: 3, name: "Charles" };
var save = _.spread(function(obj){ return data.push(obj) });
    save(newObj);

Resources