What does () mean in JavaScript
I am testing an immediately callable function in javascript. I found that when I run below code in Chrome, it throwsUncaught SyntaxError: Unexpected token )
function foo(){
console.log(1);
}();
I think the parser splits this code into two parts: function declaration and ();
. But what happens if I add in 1
between ()
, it turns out that it won't throw any error.
So, I suppose that (1);
is a valid expression, but what does it mean?
Thanks for the answer.
source to share
This is an Immediate Expression :
(function foo(){
console.log(1);
})(); // call the function here
Explanation:
Suppose you are creating a function:
function foo(){
console.log(1);
}
Now, to call this function, we do:
foo()
Now, if you saw, we just gave the function name and called it. Now we can call it on the same line as:
(function foo(){
console.log(1);
})();
Here's an article you can read .
source to share
(function(){
//code goes here
})();
Is this what you want.
Putting there is simply passing 1 as a parameter to the immediate function. If you ran console.dir (arguments) inside a function when passed to 1, it will print the number you passed.
(function(){
var args = Array.prototype.slice.call(arguments);
console.dir(args); // prints [1][
})(1);
In other words, you create a function and then call it immediately. Using().
source to share