All I Want for Christmas: Effective JavaScript — Book Giveaway

He has another reason for placing the invoking parenthesis inside with the function, which is that it’s more consistent with how we call functions in the first place.

If we have a function, we don’t call it inside of parenthesis:

function someFunc() {
    // ...
}
(someFunc)(); // a bad example of calling a function

Instead, the invoking parenthesis go directly with the function - this is the normal way of using functions, even when parenthesis are involved.

function someFunc() {
    // ...
}
(someFunc()); // a good example of calling a function

The normal thing to expect is that the function and the invoking parenthesis are directly beside each other, which helps to explain Crockford’s preference - it’s the principle of least astonishment.

(function () {
    // ...
})(); // bad - violates the principle of least astonishment
(function () {
    // ...
}()); // good - invoking parenthesis right beside the function

The second example is not as good because the parenthesis is being invoked. I’ve seen cases where the last line is not actually invoking the function, but is doing other unexpected stuff instead.

And, Crockford equates the last example with the () hanging out off the end as being visually similar to dogs balls, which helps to put the nail in the coffin.

Oh, no - I’ve seen things . . . I’ll take my leave :slight_smile:

1 Like