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

When working with templates in JavaScript, you might need a simple way to work with multi-line strings. While there are several ways to achieve this, not every solution makes 100% sense. If you just need multi-lines within your code but not within the string itself, you may be familiar with the following way.

var example = 'Lorem ipsum dolor sit amet' +
    'consetetur sadipscing elitr' +
    'sed diam nonumy eirmod tempor invidunt';

However, string upon string of concatenated JavaScript grows messy and ugly pretty quickly and is also a slow way to achieve the goal. The same goes for creating an array and joining it.

var example = [
    'Lorem ipsum dolor sit amet',
    'consetetur sadipscing elitr',
    'sed diam nonumy eirmod tempor invidunt'
].join();

A solution many novice JavaScript developers aren‘t aware of is the following one.

var example = 'Lorem ipsum dolor sit amet\
    consetetur sadipscing elitr\
    sed diam nonumy eirmod tempor invidunt';

Adding a backslash at the end of each line tells the JavaScript engine that the string will continue to the next line. Furthermore this second solution creates a string including line breaks within the string itself. But be warned: not every browser will insert line breaks at the continuance, while others will. Google’s JavaScript style guide recommends to use string concatenation instead of escaping newlines because the latter isn’t part of ECMAScript. However, all of the above won’t bring you multi-line strings at all. It’s actually just line-continuation. Adjusting the solutions above by adding line-break characters does the job but makes the solutions even more messy and ugly.

var example = 'Lorem ipsum dolor sit amet\n' +
    'consetetur sadipscing elitr\n' +
    'sed diam nonumy eirmod tempor invidunt';
var example = [
    'Lorem ipsum dolor sit amet',
    'consetetur sadipscing elitr',
    'sed diam nonumy eirmod tempor invidunt'
].join('\n');
var example = 'Lorem ipsum dolor sit amet\n\
    consetetur sadipscing elitr\n\
    sed diam nonumy eirmod tempor invidunt';

An initially confusing but working "trick" to solve this problem is wrapping the text within a block comment within an anonymous function.

var example = (function() {/*
Lorem ipsum dolor sit amet
consetetur sadipscing elitr
sed diam nonumy eirmod tempor invidunt
*/}).toString().match(/[^]*\/\*([^]*)\*\/\}$/)[1].trim();

The anonymous function is converted to a string and the content of the comment is extracted. While this does indeed work fine in the browser, it’s slower than string concatenation and mainly intended for use in node.js. The last way to create legible multi-line strings in JavaScript is to use templates.

<script type="text/template" id="example">
Lorem ipsum dolor sit amet
consetetur sadipscing elitr
sed diam nonumy eirmod tempor invidunt
</script>
var example = document.getElementById('example').innerHTML;

By setting the type to text/template, the script tag isn’t a script that the browser understands and thus the browser will simply ignore it. This allows you to put anything in there, which can then be extracted (see var example) later and used as a template. Note that ECMAScript 6 will have real multi-line strings by using backticks, known as a NoSubstitutionTemplate in the spec.

var example = `Lorem ipsum dolor sit amet
consetetur sadipscing elitr
sed diam nonumy eirmod tempor invidunt`;

typeof null === "object"

An initially confusing and counter-intuitive behavior of JavaScript is that the type determination of a variable being null using typeof returns "object".

var demo = null;
typeof demo; // "object"

The reason for this is that typeof will always return "object" for native non-callable objects. Actually, this stands since the beginning of JavaScript and the operator simply returns the type string of a given reference according to the table specified in the ECMAScript language specification ECMA-262 (see page 81).

A fix that would have resulted in typeof null === "null" has been proposed (via an opt-in), but was rejected as it was too late to fix the "problem" as a change of typeof null would break existing code like incorrect implementations of type checks.

Default arguments/parameters in JavaScript

When designing your functions, it’s often helpful to be able to assign default values for arguments/parameters that aren’t passed later. Unlike programming languages like PHP, JavaScript doesn’t provide this functionality inherently. Undefined arguments are, well: undefined.

var sayHello = function(name) {
    console.log('Hello, ' + name);
}

By using the shortcut computation of boolean expressions, you can define a default value for each argument which is assigned if the argument is originally undefined.

var sayHello = function(name) {
    name = name || 'Nobody';
    console.log('Hello, ' + name);
}

While sayHello('Peter') still works, sayHello() (called without any arguments) would now result Hello, Nobody. Neat.

Class constructors without using "new" in JavaScript

When creating a class constructor in JavaScript, you may prefer to allow its instantiation without using the new keyword—just like jQuery does with their $() factory function. Let’s assume the following class as a simple example.

function Person(name, age) {
    this.name = name;
    this.age = age;
}

While var jack = new Person('Jack', 32) would work, var jim = Person('Jim', 34) doesn’t—so far. Actually jim would be simply undefined after the call. But even worse: if someone calls the constructor without using new, the global scope will be poluted by the two variables name and age as calling a function without specifying its context forces the browser to pass it in the global object (which is window). By checking whether the requested object is already an instance of the class, you can return a new instance if it isn’t or execute the actual constructor if it is.

function Person(name, age) {
    if (this instanceof Person) {
        this.name = name;
        this.age = age;
    } else {
        return new Person(name, age);
    }
}

Both var jack = new Person('Jack', 32) and var jim = Person('Jim', 34) would work now. The following way does exactly the same but is a bit shorter and handier.

function Person(name, age) {
    if (!(this instanceof Person)) return new Person(name, age);
    this.name = name;
    this.age = age;
}

jQuery’s .load() callback for cached images in Internet Explorer

jQuery’s .load() function is often used if a callback function is required be executed as soon as an element is completely loaded. This is gladly used for loading images completely at first and processing certain attributes of an image (e.g. its width and height) afterwards. However, Microsoft’s Internet Explorer doesn’t execute the callback if images are cached already.

While often appending a random number (to prevent caching) is recommended for this known issue, there’s a much more resource-efficient trick: simply set the src attribute of an image after the definition of its .load() function.

$('img').load(function() {
    // do something
}).attr('src', '/new-image-source.jpg');

I see some JavaScript scripts using »!0« and/or »!1« occasionally. What does that mean exactly?

Anonymous

Those are shortcuts for true and false, making use of JavaScript’s logical NOT operator (the exclamation point) and the fact that JavaScript uses weak typing, meaning that 0, false and null all mean the same in comparisons unless you force JavaScript to compare the type as well (by using ===). Using this knowledge, you can shorten true using !0 and false using !1.

Prevent links in standalone web apps to be opened in Mobile Safari under iOS

iPhones, iPads, and iPods offer the opportunity to integrate Web apps (including an icon) just like conventional, native apps on the home screen. Those Web apps are then started in a standalone mode and behave optically just like real apps. However, a bad feature of iOS for Web app development is that links in such Web apps (which actually are simply websites that are displayed in full screen mode) automatically open in Mobile Safari—that is, the standalone app closes and switches to the Safari app. Annoying. You can use the following snippet of JavaScript (include it at the bottom of your HTML site) to prevent this.

var a = document.querySelectorAll('a[href]');
for (var i = 0; i < a.length; i++) {
    a[i].onclick = function() {
        window.location = this.getAttribute('href');
        return false;
    }
}

If you’re using jQuery in your Web app, you can use the following, much-shorter version of the snippet.

$(document).on('click', 'a[href]', function(event) {
    event.preventDefault();
    window.location = $(this).attr('href');
});

Detect Touch devices using JavaScript

The following function allows the detection of touch devices (smartphones, tablets, …) using JavaScript. As an example, this allows you to offer certain actions on a website or web application only for appropriate devices like disabling hover effects for touch devices.

function isTouchDevice() {
    return ('ontouchstart' in window);
}
Fork me on GitHub