Reputation: 2584
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:)
Upvotes: 3
Views: 134
Reputation: 13994
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/
Upvotes: 1
Reputation: 2793
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?
Upvotes: 0
Reputation: 165951
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.
Upvotes: 1
Reputation: 700212
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)))));
Upvotes: 1
Reputation: 504
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
Upvotes: 1