I'm testing immediately invoked function in javascript. I found when running below code in Chrome, it throws Uncaught SyntaxError: Unexpected token )
function foo(){
console.log(1);
}();
I think the parser break this code to two parts: a function declaration and ();. But what would happen if I add a 1 between (), turns out it won't throw any error.
So I suppose (1); is a valid expression, but what does it means?
Thanks for answer.
It is Immediately-Invoked Function Expression:
(function foo(){
console.log(1);
})(); // call the function here
Explanation:
Suppose you create 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 in the same line like:
(function foo(){
console.log(1);
})();
Here is an article you can read.
(function(){
//code goes here
})();
Is what you want.
Putting the one there simply passes 1 as a parameter into the immediate function. If you did a console.dir(arguments) inside of the function when passing in 1 it would print out the number you passed in.
(function(){
var args = Array.prototype.slice.call(arguments);
console.dir(args); // prints [1][
})(1);
In other words you create the function and then call it immediately. Using ().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With