lmirosevic
lmirosevic

Reputation: 16317

How to execute some javascript without modifying the global scope?

I want to call some javascript code that for its own purposes needs to define some variables, but I want to isolate this so it doesn't pollute the global scope. So I wrap everything in an anonymous function object, call it immediately, and don't assign it or the result to anything:

function() {
    var myInnerHelperFunction = function(object) {
        //do some work
    };

    var anObject = ...;

    myInnerHelperFunction(anObject);
}();

But I get a syntax error: SyntaxError: Unexpected token (

Upvotes: 1

Views: 43

Answers (1)

James Allardice
James Allardice

Reputation: 166001

You can't invoke a function declaration. You need to make it an expression instead. The most commonly seen technique to achieve this is to wrap the function in parentheses:

(function() {
    var myInnerHelperFunction = function(object) {
        //do some work
    };

    var anObject = ...;

    myInnerHelperFunction(anObject);
}());

However, note that any unary operator will also work (anything that causes the construct to be parsed as an expression, rather than a declaration):

~function example() {
    console.log("example");
}();

To expand upon this further, your code actually throws a syntax error because your function is missing an identifier. A "program" can only contain statements and function declarations. Therefore, your code must be parsed as a function declaration. A function declaration must have an identifier. Yours doesn't, so your program is invalid.

When you wrap parentheses around the function, the parse tree is different. The parentheses get parsed as an "expression statement", which can contain a expression. Since functions can be parsed as either expressions or declarations, depending on the context in which they appear, this is legal, and the function is parsed as an expression. Since function expressions can be immediately invoked, this works.

Upvotes: 8

Related Questions