Store Objects in JavaScripts HTML5 LocalStorage

LocalStorage is really useful. It can save variables (just like cookies) in a users browser. But there is one problem which many people seem to encounter: Storing objects does not work.

localStorage.setItem('test', { someKey: 123 });

This line of code saves our object as a string. If we restore the stored item, we will get this:

// [object Object]

This is because JavaScript calls the .toString() method on our object, which simply outputs [object Object]. If we want to store and restore objects, we need to encode them into a JSON string. The following code implements my most used solution for storing objects:

var LocalStorageManager = function() { 
    if (typeof localStorage === 'undefined') {
        throw 'localStorage cannot be used in this browser';   

LocalStorageManager.prototype.setObject = function(key, obj) {
    localStorage.setItem(key, JSON.stringify(obj));

LocalStorageManager.prototype.getObject = function(key) {
    return JSON.parse(localStorage.getItem(key));
var storage = new LocalStorageManager();
storage.setObject('user', { name: 'john', age: 26 });

Yes, you could do this without an additional object, but it keeps stuff cleaner if you use one. If you got any questions, feel free to contact me in the comment section down below.

How to win the game 2048

Here is the strategy I used to beat the popular 2048 game. It is not a guaranteed win, but I have achieved multiple scores over 10’000 points and won two times.

Tile Movement

It is very important to never use all 4 directions in one game. Choose 3 directions and only use these. I always go for left, up and right, meaning I never press down.


Most guides will tell you to choose a corner and try to hold your biggest tile there. This will most likely fail, so try to always keep the biggest tiles on top of your board. After around 5000 points you should avoid having a 2 or 4 in your top two rows, because you just can’t combine them with a 128 (or a bigger tile of course) any time soon.


As soon as you have a 1024 and two 512 tiles everything I said above becomes irrelevant and you should try to combine those to a 2048, therefore winning the game.

Now there is an algorithm that has a 90% win rate, programmed by the creator of 2048, Gabriele Cirulli. You can check out the 2048 AI here and a Stackoverflow question regarding this issue here.

What are anonymous self-invoking functions in JavaScript?

Have you ever been confused by something like this?

(function() { 
    console.log('hello world');

This function invokes itself after it has been declared, meaning it calls itself right after you have declared it. All we are doing is wrapping the function into parentheses and then call it like you would call any function with (). Think of it this way:


Some people use .call() (which does exactly the same), because the other syntax can be confusing for people who have just started with JavaScript:


To finish this post off, let us have a look at a real world example of an anonymous, self-invoking function:

var list = (function() {
    // declare variables that cannot be used outside of the function scope
    var x = 10;
    var y = 20;

    return [x, y];

// correctly logs [10, 20]

// throws a reference error

for-Loop with Delay in JavaScript

I had multiple JavaScript beginners come to me and ask me this question:
How can I create a for-loop with x ms delay in between?

This code is what most have come up with (for quick readers: not what you are looking for!):

for (var index = 1; index <= 50; index++) {
    setTimeout(function() {
    }, 100);    

Now this prints "50" fifty times, because a for-loop is synchronous while setTimout is asynchronous. This means that the for-loop is finished very fast and has startet 50 setTimeouts. After 100ms all of those setTimeout functions will fire together, therefore printing "50" fifty times. Note that the var-keyword binds variables to the function scope, not the current block scope like in other languages.

In order to create a for-loop with actual delay - in our case printing a number, waiting 100ms and printing the next number - you need to create a self-invoking, recursive function. Don't worry, it's not that hard.

var maxLoops = 50;
var counter = 0;

(function next() {
    if (counter++ >= maxLoops) return;

    setTimeout(function() {
    }, 100);

Here we declare two variables, maxLoops and counter. These are for keeping track of how many times the function has called itself. Afterwards we create the function "next", put it in brackets and call it immediately. This is why it's called a self-invoking function.

The if-statement does two things. First of all it counts up our counter variable using the ++ operator. It also returns the function if it has been called 50 times, therefore stopping the loop.

The last part is the most important. We create our setTimeout function and then call next() after the number has been printed. And that's how you create a for-loop with delay in JavaScript.

Here is an even shorter, but harder to understand solution:

(function next(counter, maxLoops) {
    // break if maxLoops has been reached
    if (counter++ >= maxLoops) return;

    setTimeout(function() {

        // call next() recursively
        next(counter, maxLoops);
    }, 100);
})(0, 50);

Simple Registry Pattern Implementation in JavaScript

Have you ever had to deal with something like this?

switch (input) {
    case '200':
        correspondingEvent = 'success';
    case '404':
        correspondingEvent = 'error';
    case '500':
        correspondingEvent = 'error';
    // etc...

A huge switch statement that you cannot dynamically change. There is a design pattern called Registry Pattern for exactly this case. It is basically an object/array which maps different conditions.

Here is a JavaScript implementation of said pattern:

var registry = {
    '200': 'success',
    '404': 'error',
    '500': 'error',
    '403': 'error',

var input = '200', correspondingEvent;

if (input in registry) {
    correspondingEvent = registry[input];   
} else {
    // handle invalid input   

Adding or removing new cases is very easy:

registry['401'] = 'error';
delete registry['401'];

I would like to thank Christian Strotz for opening my eyes on this one, since I originally used an array instead of an object. (like in most other programming languages).

My Sublime Text 2 Configuration

Here is my Sublime Text 2 configuration file. Install these packages before applying it:

  • Github Color Theme
  • Theme – Centurion
  "bold_folder_labels": true,
  "color_scheme": "Packages/Github Color Theme/GitHub.tmTheme",
  "drag_text": false,
  "folder_exclude_patterns": [
  "font_size": 10,
  "highlight_line": true,
  "line_padding_bottom": 2,
  "line_padding_top": 2,  
  "show_tab_close_buttons": false,
  "tab_size": 2,
  "theme": "Centurion.sublime-theme",
  "translate_tabs_to_spaces": true,
  "use_tab_stops": true,
  "word_wrap": true

Screenshot of the editor (looks very similar on OS X)

dark theme

Smallest JavaScript FizzBuzz solution possible?

Maybe you have seen this kind of viral picture about a guy who gets asked to program FizzBuzz in a job interview.

My friend and I tried to make the smallest possible JavaScript FizzBuzz solution possible. Here were our requirements:

  • Print numbers from 1 to 100
  • If a number is dividable by 3, print “Fizz” instead
  • If a number is dividable by 5, print “Buzz” instead
  • If a number is dividable by 3 and 5, print “FizzBuzz” instead
  • Print using console.log
  • Pure JavaScript only

First Try (101 characters)

for(n=1;n<=100;++n){s="";if(!(n%3))s="Fizz";if(!(n%5))s+="Buzz";else if(n%3&&n%5)s=n;console.log(s);}

Uses a simple if-else clause and appends the strings "Fizz" and "Buzz", so we don't need an extra "FizzBuzz" in our code.

Second Try (69 characters)


30 characters shorter! This uses some neat tricks in JavaScript. console.log logs the return value of a || operator. The || operator evaluates the left -and right-handed side of it and returns the first true value. An empty string is considered false in JavaScript, therefore it would print the number if the number is not dividable.

Third Try (64 characters)


Have a look at the for-loop on this one. Using the pre-increment operator ++ we don't need the last argument in our for-loop. We were also able to remove the parentheses in the ternary statements.

Can you make it even shorter? Reply down below!

Emulate Interfaces in JavaScript with interface.js

Interfaces are something you don’t actually need in a loosely typed language like JavaScript, but sometimes it’s nice to make sure that some methods really exist. This is where interface-js comes in handy. You can create new interfaces like this:

var IAnimal = new Interface([ 'roar', 'sleep' ]);

When you are creating your class, you can use it like this:

var Tiger = function() {

  // Implement the interface 'IAnimal'

Tiger.prototype.roar = function() {

‘Tiger’ does not implement the method ‘sleep’, so it throws an error:

InterfaceException: Missing the following method: 'sleep'

The source code for interface-js is available on GitHub. Pull requests are welcome!

Real JavaScript Enums with enum.js

I stayed at home yesterday and had nothing to do, so I tried to implement enums in pure JavaScript. It worked quite well as you can see on my GitHub profile.

Let’s get straight to the point:

var Days = new Enum([ 'Monday', 'Tuesday', 'Wednesday' ]); // to be continued


var inputDay = Days.Monday;
return (inputDay === Days.Monday) // returns true

It provides a useful .toString() method:

console.log( Days.Monday.toString() ); // logs 'Monday'

It is also protected against overwriting by using Object.freeze. If you don’t want to freeze it, you can pass it as an option when you’re creating the enum:

var Days = new Enum([ 'Monday', 'Tuesday', 'Wednesday' ], { finalize: false });

enum.js is very small and has no dependencies. Grab the source code from the GitHub repo and start creating JavaScript enums today!

Understanding Backbone View Events

When you are using Backbone, you’ve surely heard of the useful DOM-bound events provided by Backbone.View. Here is an example of such an event:

var someView = Backbone.View.extend({

  el: 'section#content',

  events: {
    'click button#save':    'saveSomething'

  saveSomething: function(event) {
    // do work


These events work only if you’ve provided the ‘el’ attribute. It represents the current context of your view. Events also require jQuery, since it uses its $.on() method to bind events to the DOM.

How it actually works

Backbone first parses your input string with this regular expression:


It breaks the string into two parts; The event name and the selector. Example:

click button#save

--> eventName: 'click'
--> selector: 'button#save'

That’s basically it. Now it just calls jQuerys $.on() like this:

this.$el.on(eventName, selector, method);

…and your event is bound to the DOM. As you can see, events can only be bound to elements within the context of your view (‘el’ attribute). This approach allows you to use any event that jQuery provides.

Events are automatically bound after the ‘render’ method. If you need to call it by hand, you can use delegateEvents.