I have a doubt regarding functions(objects) in javascript.
I have 2 pieces of code like,
var a= function(){
console.log('abc')
}
and
var a= (function(){
console.log('abc')
})
what is the difference between these two>>
thanx:)
5 Answers 5
There is no practical difference. They will both result in an anonymous function being assigned to a.
The first is a "simple assignment". In the second, the parentheses are acting as a "grouping operator", which does one thing:
The production PrimaryExpression : ( Expression ) is evaluated as follows:
- Return the result of evaluating Expression. This may be of type Reference.
So the grouping operator will return the function contained within it, and assign it to a, just like the first example.
Comments
There is no difference now, but if you add another parenthesis () after second function it will run function without invocation.
var a= (function(){
console.log('abc')
})()
it will print 'abc' straightaway
2 Comments
There is no difference. You have a function expression, and you can put any number of parentheses around an expression.
Just as this:
a = 42;
is the same as this:
a = (42);
and this:
a = (((((42)))));
Comments
There is a difference.
( and ) constitute a grouping. A grouping can only contain an expression, thus any function inside it will be an expression and not a declaration.
Since ECMA specifies that a function declaration must always have a function name, and a function expression may omit it, you will be able to do the following
(function() {});
while the following declaration is not valid
function() {};
It won't matter that often, but still... Read this in-depth article for more: http://kangax.github.com/nfe/
Comments
As has been said, the two examples you've given are essentially the same.
This question has a lot more information contained in the answers regarding parentheses usage, might be worth your time to spin through!
Why are parenthesis used to wrap a javascript function call?
(((function(){})))and it'll still be the same thing, unless what you mean is(function(){}())...