Tag Archives: JavaScript

ES6 Variable Swap Explained

The following ES6 code swaps the values of two variables:

var x = 1;
var y = 2;
[x, y] = [y, x];

It works by using a Destructuring assignment on the array [y, x]. Destructuring is used to extract values from an array or an object. You are able to do this for example:

var [month, year] = [5, 1990]

The example above creates two local variables called “month” and “year” with the respective values 5 and 1990. In the swap example we are omitting the “var” keyword and end up with two simple assignment calls (most ES6 transpilers end up creating the following code):

var x = 1;
var y = 2;
var temp = [x, y];
x = temp[1];
y = temp[0];

Observer Pattern in JavaScript

Here is a simple, straight-forward observer implementation in JavaScript that you can use in any modern JavaScript environment. Please note that IE8 and below cannot use Array.prototype.filter and Array.prototype.forEach.

var Observable = {
  listeners: [ /* { event: String, fn: Function } */ ],
  _addListener: function(event, fn) {
    this.listeners.push({ event: event, fn: fn });
  },
  _removeListener: function(event) {
    this.listeners = this.listeners.filter(function(listenerObj) {
      return listenerObj.event !== event; 
    });
  },
  on: function(event, fn) {
    this._addListener(event, fn);  
  },
  off: function(event) {
    this._removeListener(event);  
  },
  listenTo: function(target, event, fn) {
    target._addListener(event, fn);
  },
  trigger: function(event) {
    this.listeners.filter(function(listenerObj) {
      return listenerObj.event === event; 
    }).forEach(function(listenerObj) {
      listenerObj.fn(listenerObj.event); 
    });
  },
};

You can set this object to a prototype of any of your classes:

// new class Person
var Person = function(name) {
  this.name = name;
};

// inherit from Observable
Person.prototype = Observable;

// define getName method
Object.defineProperty(Person.prototype, 'getName', {
  writable: false,
  value: function() {
     return this.name;  
  }
});

Any object that you instantiate from “Person” now is observable. This means you can easily do the following:

var jon    = new Person('Jon Snow');
var tyrion = new Person('Tyrion Lannister');

jon.listenTo(tyrion, 'greeting', function(event) {
  console.log('Received a ' + event + ' from ' + tyrion.getName());
});

jon.on('bye', function(event) {
  console.log('Received a ' + event + ' from ' + jon.getName());
});

tyrion.trigger('greeting'); // "Received a greeting from..."
jon.trigger('bye'); // "Received a bye from..."

jon.off('bye'); // unbinds all 'bye' listeners
jon.trigger('bye'); // does not fire anything

The syntax is very similar to Backbone, but of course without any dependencies. This code works best in a modern NodeJS environment where you do not need to support old JavaScript implementations. Bitbucket repository.

This code makes no sense.. Or does it?

[!+[]+!+[]]+[+[]]+[+!+[]]+[!+[]+!+[]+!+[]+!+[]]

Beautiful right? This messy line of brackets, exclamation points and plus signs evaluates to the string “2014”. You can try it by pasting it into your browsers console or using Node.js.

Let’s have a closer look at the first part of it:

[!+[]+!+[]]

This produces an array with one entry: 2. If we break it down even further, it starts to make sense:

+!+[]

This code consists of four elements (differently colored). On the right we got a simple, empty array. The plus sign in front of it automatically casts it into a number, because that’s how loosely typed languages work. We can prove it by running this:

Number(new Array())

Alright, so casting an array into a number results in 0.  The next element we need to look into is the exclamation point. The “!” operator inverts a boolean. But our 0 from above is not a boolean. No problem, JavaScript just casts it into one like we would expect it to do in “normal” code. We are now left with this:

!+[]

All we have to do now is simply cast true back into a number by using the plus operator:

+!+[]

Now if we chain two of those together, we get our first value of “2014”; “2”!

+!+[]+!+[]

And that’s the whole magic. The rest is pretty much the same, I won’t explain it all here. There is a site called JSFuck.com which can produce this kind of code. Quite interesting!

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:

localStorage.getItem('test');
// [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 });
console.log(storage.getObject('user'));

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.

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:

(function)();

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

(function).call();

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]
console.log(list);

// throws a reference error
console.log(x);

for-Loop with Delay in JavaScript

Update November 2016:

While this post is still valid for ES5, I wanted to point out that there is now an easier method using async/await in the latest TypeScript 2.1.0 release. You can use this feature natively in the latest Node version, but TypeScript now allows you to compile async/await to ES5 for browsers.

You should still read the original post, especially if you found this blog entry while googling a similar problem.

const delay = (amount: number) => {
  return new Promise((resolve) => {
    setTimeout(resolve, amount);
  });
};

async function loop() {
  for (let i = 0; i < 50; i++) {
    console.log(i);
    await delay(100);
  }
}

loop();

Original Post

I've had multiple JavaScript beginners ask me this how they can create a for-loop with delay. 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() {
        console.log(index);
    }, 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 started 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() {
        console.log(counter);
        next();
    }, 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 one. 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() {
        console.log(counter);

        // 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';
        break;
    case '404':
        correspondingEvent = 'error';
        break;
    case '500':
        correspondingEvent = 'error';
        break;     
    // 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).

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 divisible by 3, print “Fizz” instead
  • If a number is divisible by 5, print “Buzz” instead
  • If a number is divisible 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)

for(n=1;n<101;++n)console.log(((n%3)?'':'Fizz')+((n%5)?'':'Buzz')||n)

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 divisible.

Third Try (64 characters)

for(n=0;++n<101;)console.log((n%3?'':'Fizz')+(n%5?'':'Buzz')||n)

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'
  IAnimal.implement(this);
};

Tiger.prototype.roar = function() {
  console.log('ROARRR');  
};

‘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!