Question

What is the different between two declarations of a module in JavaScript? One has parentheses around the function and other one doesn't?

One article says that

Notice the () around the anonymous function. This is required by the language, since statements that begin with the token function are always considered to be function declarations. Including () creates a function expression instead.

Both seem to do the same thing when checked.

var person = (function () {
    // Private
    var name = "Robert";
    return {
        getName: function() {
            return name;
        },
        setName: function(newName) {
            name = newName;
        }
    };
}());

var person = function () {
    // Private
    var name = "Robert";
    return {
        getName: function() {
            return name;
        },
        setName: function(newName) {
            name = newName;
        }
    };
}();
Was it helpful?

Solution

Functions are of two types in JavaScript - declarations and expressions.

This is the difference between the two:

  1. Function declarations are hoisted. This means you can call the function before it appears in the program as declarations in JavaScript are hoisted.
  2. Function expressions can be invoked immediately. A function declaration cannot. This is because expressions express (or return a value). Function expressions express a function.

An example of a function declaration:

foo("bar");

function foo(bar) {
    alert("foo" + bar);
}

The above program will work because foo is a function declaration.

foo("bar"); // throws an error, foo is undefined - not a function

var foo = function (bar) {
    alert("foo" + bar);
};

The above program will not work as foo is declared as undefined, hoisted and then later assigned the value of a function expression. Hence it's undefined when it's called.

An example of a function expression:

(function (bar) {
    alert("foo" + bar);
}("bar"));

The above function will be immediately invoked as it's a function expression.

function (bar) {
    alert("foo" + bar);
}("bar"); // throws an error, can't call undefined

The above function will not be immediately invoked as it's a function declaration. Remember, declarations do not express (or return a value). So it's like trying to invoke undefined as a function.

How does a function become an expression?

If a function is used in the context where an expression is expected then it's treated as an expression. Otherwise it's treated as a declaration.

Expressions are expected when:

  1. You're assigning a value to a variable (i.e. identifier = expression).
  2. Inside parentheses (i.e. ( expression )).
  3. As an operand of an operator (i.e. operator expression).

Hence the following are all function expressions:

var foo = function () {};
(function () {});
~function () {};

Everything else is a function declaration. In short if your function is not preceded by anything, it's a declaration.

See this code: https://github.com/aaditmshah/codemirror-repl/blob/master/scripts/index.js#L94

The following function isExpression is used to test whether some arbitrary JavaScript code is an expression or not:

function isExpression(code) {
    if (/^\s*function\s/.test(code)) return false;

    try {
        Function("return " + code);
        return true;
    } catch (error) {
        return false;
    }
}

Hope this clears any doubts in your mind.

In short:

  1. A function expression expresses or returns a value (in this case a function). Hence it can be immediately invoked, but it can't be called before it appears in the program.
  2. A function declaration is hoisted. Hence it can be called before it appears in the program. However since it doesn't express any value it can't be immediately invoked.

OTHER TIPS

In the current context there's no difference for the interpreter. Usually preferable way of writing module is by wrapping the function with parentheses:

var person = (function () {
    // Private
    var name = "Robert";
    return {
        getName : function () {
            return name;
        }
    };
}());

That's because the syntax is cleaner and it's obviously that you want to invoke the function immediately after it is declared. One more reason is because:

(function () {
    //some stuff
}());

will work but

function () {
    //some stuff
}();

this wont.

By wrapping the function each time you use common codding style which is usually a good thing :-).

The difference is that when writing:

var foo = (function () {
          ...
}());

the use of the (superfluous but useful) grouping () is a common coding style to make it clear from very like first line that the right hand side is most likely an immediately invoked function expression (IIFE). However, in the second:

var foo = function () {
          ...
}();

it doesn't become apparent until you read the last line, which might be quite a few lines down. Until you reach the last line, you probably thought you were reading a plain assignment:

var foo = function () {
          ...
};

Note that the parenthesis can be used in a plain assignment too:

var foo = (function () {
          ...
});

but in that case they really are superfluous (and probably misleading due to the convention of using them for IIFEs).

See An Important Pair of Parens.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top