17 Sep 2014

JavaScript Closure and Design Patterns in 3 minutes (or more)

1st Minute: What is a closure in Javascript?

A closure is not really a thing. It is just a term we use to describe what happens when we have a function that has access to outside variables other functions cannot access.

Outside variables are sometimes referred to as non-local variable.

Here is a simple example of closure in JavaScipt.

Now everytime you do cat(), a new variable, nyan, would be created. And nyan is only accessible by the speak function inside cat.

Here is another example of closure.

Now when you invoke cat, 3 variables will be created: an array nyan, an integer x, and a function speak_and_change_x. Both nyan and x can only be accessed by function speak_and_change_x inside cat.

Since you are just returning speak_and_change_x, rather than invoking it using (), nothing will be alerted when you write cat(). However, writing cat()() will alert (“meow”) because it is equivalent to invoking the function cat returns - and that is the same as speak_and_change_x().

Rather than writing cat()() to invoke the function, normally what we do is to store what cat() returns into a variable.

Note: when returning a function, you shouldn’t put () behind it. The moment you put () behind a function, you are invoking/invoking it.

Click here if you are curious what invoking alert(c) will do in the code above.

● ● ●

Bonus: Ternary Operator

In the example above you can see that I am doing something like this:

This is a short way of writing

The way it works can be visualized in this form:

Bonus: Strict Comparison Operators (=== and !==)

The === in the code above is known as a Strict Comparison Operator. It is slightly different from ==. When we compare two variables like this: a === b, the JavaScript engine will first look at the variables’ types, and if they are not the same type, false will be returned immediately.

If we compare two variables using ==, a type conversion would happen before the comparison occurs.

Therefore, in terms of performance, === would be slightly faster. The other strict comparison operator is !==, which is simply the inverse of ===.

● ● ●

2st Minute: More on Closure in JavaScript

When you create a closure, instead of returning a function, you can return an object. Here is another example of closure.

In the example above, by returning an object, you will be able to return 2 functions that can access nyan and x, which other functions has no access to.

Functions in the form function(){…} is known as anonymous function. One cool thing in JavaScript is that functions are actually not required to have names.

By having a function like this (function(){…})() (enclosing it with brackets and putting another pair of brackets behind), we are basically invoking this anonymous function. The () behind can also be used to pass parameters into the function, just like what can be done using () behind a function name like this alert(“nyan”).

One common practice in Java script is to pass commonly used variables into anonymous function as parameters for quicker access. By passing a variable into a function, you would be able to access it locally instead of globally when you are inside the function, and thus it would be relatively faster.

When you surround statements (e.g. a function statement: function hi(){}) in brackets (i.e. you have (function hi(){})), you are turning them into expressions (in this case it’s known as immediately-invoked function expression (IIFE)) and you can do all sort of things with expressions, similar to how you can do all sorts of things with variables.

3rd Minute: Design patterns in JavaScript

The example above where we create a closure and return an object is an example of a design pattern in JavaScript known as The Module Pattern.

There are many design patterns in JavaScript. Different design patterns are just different ways of writing codes. The Module Pattern, for example, uses closure to create the illusion of a class object (or a class instance), something that JavaScript doesn’t really provide (since JavaScript implements prototype-based OO). Using The Module Pattern, one would be able to have public and private functions and variables in an object (as if it is an instance of a class in class-based OO).

In this case, x and nyan are private variables, while name is a public variable and speak() and transform() are public functions. In class-based OO language, when something is public, it simply means that it is globally accessible. When something is private, only the instance and class functions (In this case there isn’t a class function) are able to access it.

Now let’s move on to The Singleton Pattern, another beginner design pattern that makes good use of closure. The Singleton Pattern is like an upgrade version of The Module Pattern. Besides creating an illusion of a class object, it creates an illusion of a class function that either constructs the object (an instance of the class) or returns an already constructed object.

Basically, in the Singleton Pattern, we restrict instantiation of a class to a single object.

(From the example above:)

Here we can see that nothing will happen to the variable instance. And it would be returned if instance is not undefined.

Conclusion: in The Singleton Pattern, the object/instance can only be accessed using the Archy.get_cat() function. So Archy is acting like the agent of the cat. There is no other way to get the cat unless you ask Archy. And Archy would create the cat for you the first time you ask for the cat. After that Archy would just keep giving you the same old cat.


If you’d like to learn more about JavaScript’s design patterns, here is a great book written by Addy Osmani.


Handcarfted by Archy Wilhes 魏何

Frontend consists of vanilla JS, CSS & HTML with Bootstrap
Backend written exclusively in Haskell using Hakyll

See you around.