Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does () mean in JavaScript

Tags:

javascript

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.

like image 770
CunruiLi Avatar asked Feb 12 '26 14:02

CunruiLi


2 Answers

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.

like image 128
Ajay Narain Mathur Avatar answered Feb 14 '26 04:02

Ajay Narain Mathur


(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 ().

like image 45
endy Avatar answered Feb 14 '26 03:02

endy