Category Archives: Web

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!

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

Usage:

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:

/^(\S+)\s*(.*)$/

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.

How to use Underscore.js Templates in your Application

Recently I’ve posted about Mustache.js, a logic-less templating engine in JavaScript. Now, if you need advanced templates with logic, you can use Underscore.js. If you are using Backbone.js, you have it included anyways.

Here’s some test data I’ve made for generating HTML with the _.template() method from Underscore.js:

var collection = [
    {
        name: 'Patrick',
        age: 19,
        lastMatches: [
            {
                champion: 'Jax',
                hasWon: true
            },
            {
                champion: 'Vayne',
                hasWon: true
            }
        ]
    },
    {
        name: 'Kha',
        age: 18,
        lastMatches: [
            {
                champion: 'Ezreal',
                hasWon: false
            },
            {
                champion: 'Lee Sin',
                hasWon: true
            }
        ]
    },
    {
        name: 'Abu',
        age: 17,
        lastMatches: [
            {
                champion: 'Elise',
                hasWon: true
            },
            {
                champion: 'Shaco',
                hasWon: false
            }
        ]
    }
];

Now here is the corresponding Underscore template that you could include in a templates.html file.

<script type="text/template" class="template">
     <p> <%= name %> </p>
     <ul>
         <% _.each(lastMatches, function(match) { %>
             <% var color = (match.hasWon) ? 'green' : 'red'; %>
             <li class="<%= color %>"> <%= match.champion %> </li> 
         <% }); %>
     </ul>
</script>

By using these ERB-style delimiters <% %>, you can have JavaScript code in your template. Printing out a single variable is really easy:

<%= color %>

Finally, all we have to do is combining those pieces of code:

var compileHTML = _.template(jQuery("script.template").html())

_.each(collection, function(entity) {
   this.$el.append(compileHTML(entity)); 
});

See? Dead easy. Since we are using this template more than once, I’ve compiled it into the variable ‘compileHTML’. This speeds everything up. If you need to know something else, have a look at the documentation of Underscore.js.

Model, View and Router Extension/Inheritance in Backbone.js

Backbone.js supports inheritance of models, views and controllers. It’s pretty easy to understand and use, here is an example:

var Animal = Backbone.Model.extend({
    defaults: {
        name: 'Animal'
    },
    eat: function() {
        return this.get('name') + ' enjoys some food.';
    }
});

We started by declaring a class named ‘Animal’. It has one method and one attribute. Let’s extend it:

var Dog = Animal.extend({
    chaseCar: function() {
        return this.get('name') + ' is chasing a car.';
    }
});

By calling the Model.extend() method on our previously created class ‘Animal’, we can extend its functionality. In this example, we will create a ‘Dog’ model that inherits everything from ‘Animal’. We can test that by calling the Animal.eat() method on ‘Dog’:

var instance = new Dog({ name: 'Buddy' });
console.log(instance.eat());
console.log(instance.chaseCar());
Buddy enjoys some food.
Buddy is chasing a car.

If you are creating custom error models, this can be extremely useful. Inheritance is a common thing in other languages and I’m very happy to see it in JavaScript.

Introduction to Mustache.js

If you want to create an application that runs mostly in the users browser, you will have to render HTML in JavaScript. To do that efficiently, you should use a template framework. In my opinion, the best one you can currently use is mustache.js. Here are some examples:

Variables

var view = {
    name: 'Patrick',
    age: 19
};

var template = '{{name}} is {{age}} years old.';

var output = Mustache.render(template, view);

Output

Patrick is 19 years old.

 

Lists

var view = {
    name: 'Patrick',
    friends: [
        { name: 'Joel' },
        { name: 'Pascal' },
        { name: 'Tobias' }
    ]
};

var template = 'Here are {{name}}s friends: {{#friends}}{{name}} {{/friends}}';

var output = Mustache.render(template, view);

Output

Here are Patricks friends: Joel Pascal Tobias

 

True/False Switches

var view = {
    name: 'Patrick',
    hasCar: true
};

var template = 'This is {{name}}. {{#hasCar}}He owns a car.{{/hasCar}}';

var output = Mustache.render(template, view);

Output

This is Patrick. He owns a car.

 

If used correctly, this can be a huge help. Check out mustache.js on GitHub and a jQuery compatible version here. Happy coding.