Consynchronous Assurency: How to achieve quasi-concurrency with Array.prototype.forEach

One of the most important concepts in JavaScript is asynchronous programming. The standard model for this technique looks like this:

doSomething(some, args, function(error, result) {
  /* callback */
});

Basically, when you call doSomething(), there is no actual return value. Instead, the results are passed as an argument to a provided lambda function. Whenever you used setTimeout(), all you did is an exercise in asynchronous programming.

Side note: At least in Node.js, all callbacks are assumed to have a signature where the error argument comes first. And really, your code should comply with that unwritten law.

However, there is a common »problem«: Asynchronous code does not imply concurrency, where a multitude of »code frames« (i.e. threads) is executed in quasi-parallel. JavaScript doesn’t know threads. What it can do, is letting you create different code frames, which are executed independently, i.e. with said setTimeout(), which you can use to decouple a block of code from your current execution frame. But at any time only one of these frames is active.1

A typical example where concurrency might be useful is array.forEach(). Suppose you want to do quite complex, time consuming computations by iterating over each item in an array. First attempt:

arr.forEach(function(val, idx) {
  /* super complex code goes here */
});

What happens is that each item in the array is processed in order, but not concurrent. At all times, there is only one instance of the lambda function running, each handling one item after another. The real problem comes from the fact that forEach() blocks, just like the following piece of code, which is old as hell:

for(var i = 0; i < arr.length; i++) {
  /* ... */
}

Now, how can we combine the two concepts, concurrency and asynchronicity, so that code like this doesn’t block? Well, just wrap your lambda in another lambda, that calls setTimeout():

arr.forEach(function(val, idx) {
  setTimeout(function() {
    /* actual code goes here */
    console.log('foo ' + idx);
  }, 0);
});

console.log('bar');

That code will always output »bar« first, thus the interpreter directly continues with the main code path and calls your lambdas later. Notice that it is perfectly legal to have a timeout value of zero milliseconds, meaning that the function is called as soon as possible. While there is no guarantee that all array items are processed in order (most times they are), at least your code becomes responsive again.

There was once the idea of setImmediate(), which does exactly the same as setTimeout(func, 0)—but the equality of both approaches is the reason why it’s unlikely we may ever see it in the wild.2


  1. Well, it is not absolutely true. With the Web Workers API you can sort of mimic thread-like behavior in the browser, but it’s often an overkill approach. In Node.js there is the Cluster core module. 

  2. setImmediate() is currently available in IE10 and Node.js. The latter also knows the process.nextTick() method, which again is used to decouple parts of code and is said to be more efficient. 

Difference between ».apply()«, ».call()« and ».bind()« in JavaScript

When working with functions in JavaScript, the value of this and the functions’ arguments are important. .apply(), .call() and .bind() allow you to change this inside a function and pass arguments in different ways.

The difference between .apply() and .call() is that .apply() lets you invoke the function with arguments as an array while .call() requires the arguments to be listed explicitly.

A useful mnemonic for this is…

  • apply() for arguments as an array
  • call() for comma-separated arguments

Let’s have a look at a simple example to understand what this means.

function demo(name, age) {
    alert('My name is ' + name + ' and I am ' + age + ' years old');
}

demo('John', 25);

demo.apply(this, ['John', 25]);

demo.call(this, 'John', 25);

All three function calls above do exactly the same. Both .apply() and .call() can be called on functions, which they run in the context (= the root scope in this case) of the first argument. Thus, you can use .apply() if you don’t know the number of arguments you’ll be passing or if the arguments are already in an array or array-like object (like the arguments object) and use .call() otherwise since there’s no need to wrap the arguments in an array.

Whereas .bind() is used when you want a function to later be called with a certain context—which is useful in events. While .apply() and .call() call the function immediately, .bind() creates and returns a new function that—when executed later—will have the correct context (= bound to a different this) set for calling the original function. This way you can maintain context in asynchronous callbacks and events.

var pollute = function() {
    this.innerHTML = 'Demo';
};

document.getElementById('demo').addEventListener('click', function() {
  window.setTimeout(pollute.bind(this), 1000);
});

You can also append extra parameters after the first parameter and .bind() will pass those values into the original function before passing in the extra parameters you pass to the bound function.

var sum = function(a, b) {
    return a + b;
};

var addTo = sum.bind(this, 123);

console.log(addTo(456)); // = 579

Complex/variable object keys in JavaScript

While it’s pretty easy to use regular keys within objects in JavaScript, you may need to use complex keys (e.g. variable keys) from time to time. Using square bracket notation, that’s just as easy as regular keys.

var demo = {};

demo.a = 'Easy peasy';

demo['b'] = 'Same thing in square bracket notation';

var test = 'a b c';

demo[test] = 'Variable key';

The code above results the following object.

{
    "a": "Easy peasy",
    "b": "Same thing in square bracket notation",
    "a b c": "Variable key"
}

Passing arguments to another function in JavaScript

If you want to pass arguments to another function in JavaScript, you can use .apply() to have the same access to arguments.

function a() {
    b.apply(this, arguments);
}

function b() {
    console.log(arguments);
}

a('Lorem', 'ipsum');​

Prefixing immediate functions with a semicolon in JavaScript

As your scripts may be used together with some other scripts you can’t influence/change, you should always prefix your immediate functions with a semicolon—here’s why.

Let’s assume the following function is stored within vendor.js

var someVendorFunction = function() {
    console.log(arguments);
}

…and your own scripts (wrapped in a immediate function) are stored within app.js

(function(window, undefined) {
    window.app = {};
})(window);

As the variable declaration within vendor.js is missing a semicolon at its end (e.g. as a result of minification or by relying on JavaScript’s semicolon insertion), your function gets directly appended to the incomplete variable declaration, resulting in an error.

Uncaught TypeError: undefined is not a function

As you’re not able to control scripts that get concatenated together with your scripts, the best way to prevent such errors is to prefix your immediate functions with a semicolon.

;(function(window, undefined) {
    window.app = {};
})(window);

»Truthy« and »falsy« values in JavaScript

The terms »truthy« and »falsy« are an essential feature (not a bug!) of the JavaScript language, stating that values aren’t just true when talking about »truthy« neither just false when talking about »falsy«. What’s meant is that values coerce to true or false when evaluated in a boolean context. Thus, something which evaluates to true is truthy and something which evaluates to false is falsy.

Let’s have a look at a simple function to test a value for its truthiness/falsiness.

function checkTruthiness(value) {
    console.log(value ? 'Truthy' : 'Falsy');
}

This function takes the value parameter and evaluates it in a boolean context (= the condition of the ternary if-statement). As a result, all of the following values are truthy values.

checkTruthiness(true);

checkTruthiness({});

checkTruthiness([]);

checkTruthiness('Lorem ipsum');

checkTruthiness(1.23);

checkTruthiness(new Date());

While there are a lot of truthy values in JavaScript, there are actually only six falsy values. Thus, memorizing that list is the easiest way to tell whether a value is truthy or falsy.

checkTruthiness(false);

checkTruthiness(null);

checkTruthiness(undefined);

checkTruthiness(NaN);

checkTruthiness(0);

checkTruthiness('');

Looking for an example where truthiness/falsiness is actually helpful? Assuming you want to make sure a user name is set before you’re saving the user to your database, you could do a explicit check on all single possibilities manually…

if (user.name !== undefined && user.name !== null && user.name !== '') {
    users.push(user);
}

…or you make use of the falsiness of those values.

if (user.name) {
    users.push(user);
}

However, there some caveats to keep in mind.

  • If 0 as an username was meaningful, your user wouldn’t be able to register as 0 evaluates to false. Or if a user has to specify how many children he/she has, if (user.children) { … } would exclude all people who validly specified the information but don’t having any children.
  • Truthiness isn’t the same as == true. While if (expression) { … } checks for truthiness, x == y uses conversions to determine equality. It’s not exactly the same concept and the algorithm for loose equality is much more complicated than for truthiness.
  • It’s possible to explicitly wrap a primitive (string, number, null, undefined, boolean) in an object, making it truthy. For example, while 0 is falsy, new Number(0) is truthy. An even scarier example is new Boolean(false) which is also truthy.

How to fix »EACCES« errors with npm on Mac OS X

If you installed Node.js and npm using root permissions, you might end up with some nasty npm ERR! Error: EACCES errors as soon as you’re trying to install packages from npm. Consequently, you need to prefix your npm commands using sudo every time you want to install a package—which is anything but ideal. It seems that those problems are a result of using the .pkg installer provided on the Node.js website.

So, instead of running sudo npm install … each and every time, you can address the underlying issue by changing the permissions/ownership of two directories on your machine.

sudo chown -R `whoami` ~/.npm
sudo chown -R `whoami` /usr/local/lib/node_modules

Now you should be able to use npm without sudo.

Don’t use fat arrows in CoffeeScript just because of »this«

New Coffeescript programmers usually struggle with understanding the differences between -> and => function definitions. In order to clarify this common case of confusion, it helps to look at how such functions are compiled down to JavaScript.

class A

    constructor: () ->
        @funcA()
        @funcB()

    funcA: () ->
        return 'funcA'

    funcB: () =>
        return 'funcB'

a = new A
var A, a,
  __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };

A = (function() {
  function A() {
    this.funcB = __bind(this.funcB, this);
    this.funcA();
    this.funcB();
  }

  A.prototype.funcA = function() {
    return 'funcA';
  };

  A.prototype.funcB = function() {
    return 'funcB';
  };

  return A;

})();

a = new A;

By using ->, funcA is simply attached to the prototype of class A. When using fat arrows, however, CoffeeScript casts a shadow around the original function, using apply() to glue it to the class instance. Therefore such functions always have the same this (@) context, no matter where they are called. The difference may be tiny, but very important. In order to find out when to use which arrow style, two questions need to be asked:

  1. Do you use this (@) in the function?
  2. Do you want to execute the function later, possibly from a different scope?

If both questions were answered positive, then using => is the right choice.

A typical example might look like this:

class A

    constructor: () ->
        @name = 'CoffeeScript'
        @values = [1, 4, 9].map(@funcA)
        console.log(@values)

    funcA: () ->
        return @name

a = new A

This will break because funcA is implemented with -> and the function is called in the context of map, where @name won’t be defined. By using =>, it doesn’t matter where and how to call the method as its context is permanently bound to the object:

class A

    constructor: () ->
        @name = 'CoffeeScript'
        @values = [1, 4, 9].map(@funcA)
        console.log(@values)

    funcA: () =>
        return @name

a = new A

Mentioned in the article »Understanding Fat Arrows (=>) in CoffeeScript«, a good rule of thumb might be:

  • Use => when you want @ to be the object in which the method is defined.
  • Use -> when you want @ to be the object in which the method is executed.

Another interesting example, that deals with context and scope in CoffeeScript, shows why the differentiation keeps being important even in tiny scripts:

class A
    constructor: () ->
        a = () -> console.log(@)
        a()

a = new A()

The output will be the window object because a new scope is being created by declaring a -> function in the constructor of class A. A better approach would be to bind the method’s context to the object using a fat arrow:

class A
    constructor: () ->
        a = () => console.log(@)
        a()

a = new A()

Before using single or fat arrows, one has to ask the two important questions mentioned above in order to find out which arrow style fits best.

Override JavaScript functions

It‘s very easy to override functions in JavaScript. You simply assign another function to the function name.

var myFunction = function() {
    // do something...
};
myFunction = function() {
    // do something different...
};

But it’s also possible to extend the existing function in order to execute something before or after the existing function.

myFunction = (function() {
    var oldMyFunction = myFunction;
    return function() {
        // do something before...
        oldMyFunction.apply(this, arguments);
        // ...and after
    }
})();

The new variable oldMyFunction is required as the function would call itself over and over again otherwise. By using apply() and the arguments array, you don’t have to worry about the parameters as all passed parameters will be looped through.

This code definitely won’t win any beauty contests and may not be simple to understand, but may be useful for extending module code.

Multi-line strings in JavaScript