JAyP JAyP - 6 months ago 7
Node.js Question

Why is this function executed?

I need help with understanding how the following script is working.

var foo = function() {
console.log("A");
}

(function() {
// Empty
})


When running this script with node (v5.9.1) the output is "A". I would expect it to just do nothing. Why is foo executed here? I can either delete the first or last three lines and then there is no output.


  • Edit: it works as expected if I place a
    ;
    after the curly bracket on line 3. But why?


Answer

If you put (...) immediately after a function expression, you execute that function.

The code in the question defines a function which calls console.log. Then it calls that function (passing it an argument (which isn't used) of a function which does nothing anyway). Then it assigns the return value of calling the first function to foo.

It could be rewritten as:

var function_a = function() {console.log("A");};
var function_b = function() {};
var foo = function_a(function_b);

… with the only side effects being the creation of the function_a and function_b variables.


Semi-colon insertion is usually considered harmful because it leads people to expect whitespace to separate the statement into two unrelated expressions.

JSHint would warn you of the problem:

7 Missing semicolon.