Cinque
Cinque

Reputation: 115

What's the difference between the following ways of definition in JS?

code block 1:

var a = (function(){
    var obj = {a:'1',b:'2'};
    return obj;
})();
console.log(a);  

code block 2:

var a = function(){
    var obj = {a:'1',b:'2'};
    return obj;
}();
console.log(a);  

I know the results of console.log are the same.But is there any difference during the execution procedure?

Upvotes: 1

Views: 47

Answers (2)

mohamedrias
mohamedrias

Reputation: 18566

var a = (function(){
    var obj = {a:'1',b:'2'};
    return obj;
})();
console.log(a);  

The function is an IIFE (Immediately invoked function expression).

The function will be invoked and the returned value will be assigned to a.

In the second expression, Only the syntax differs, but the functionality is same. But as a good practice, it's good to wrap the function within (). If you use just below code, it will give error.

function(){
    var obj = {a:'1',b:'2'};
    return obj;
}();

Whereas

(function(){
        var obj = {a:'1',b:'2'};
        return obj;
    }());

and

(function(){
        var obj = {a:'1',b:'2'};
        return obj;
    })();

both won't give error, because we are explicitly defining it to be treated as a expression.

Upvotes: 1

Quentin
Quentin

Reputation: 943193

The only effect that putting parenthesis around a function has is to ensure it is treated as a function expression.

Putting it as the RHS of an assignment also has that effect.

Consequently, there is no difference between the two.

Upvotes: 2

Related Questions