The function Statement Versus the function Expression

JavaScript has a function statement as well as a function expression. This is confusing because they can look exactly the same. A function statement is shorthand for a var statement with a function value.

The statement:

function foo(  ) {}

means about the same thing as:

var foo = function foo(  ) {};

Throughout this book, I have been using the second form because it makes it clear that foo is a variable containing a function value. To use the language well, it is important to understand that functions are values.

function statements are subject to hoisting. This means that regardless of where a function is placed, it is moved to the top of the scope in which it is defined. This relaxes the requirement that functions should be declared before used, which I think leads to sloppiness. It also prohibits the use of function statements in if statements. It turns out that most browsers allow function statements in if statements, but they vary in how that should be interpreted. That creates portability problems.

The first thing in a statement cannot be a function expression because the official grammar assumes that a statement that starts with the word function is a function statement. The workaround is to wrap the whole invocation in parentheses:

(function (  ) {
    var hidden_variable;

    // This function can have some impact on
    // the environment, but introduces no new
    // global variables.
}());

Get JavaScript: The Good Parts now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.