1

Have seen many usage in this format:

(0, function(a, b){console.log(a + b)})(3, 4)

What is 0 for?

JJJ
  • 32,902
  • 20
  • 89
  • 102
Hom
  • 421
  • 1
  • 4
  • 7
  • 1
    `function(a, b){console.log(a + b)}(3,4)` is not a valid syntax. That's why the author of that code used comma expression to call it. Author would have written the same code like, `(function(a, b){console.log(a + b)})(3,4)` – Rajaprabhu Aravindasamy Sep 19 '16 at 06:58
  • @RajaprabhuAravindasamy but `(function(a, b){console.log(a + b)})(3,4)` is valid – Hom Sep 19 '16 at 07:04
  • It's just another IIFE syntax. I also don't understand why the author chose to use a comma – evolutionxbox Sep 19 '16 at 07:07

2 Answers2

-1

That 0 is ignored.

That comma is the comma operator:

The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.

Basically that 0 is evaluated as 0 then that function expression is evaluated and since the function is the last thing evaluated in the comma list a function reference to it is returned. It is that returned function that is called.

In the code in your question, the 0 is therefore completely useless.

However, it could be that the author intended this instead:

0,function(a, b){console.log(a + b)}(3, 4);

Which saves typing two characters ( and ) but then it takes two characters anyway so it's not very useful.

slebetman
  • 109,858
  • 19
  • 140
  • 171
-1

It serves the same purpose as a parenthesis or a bang prefix.

0 is an expression that has no effect. The comma operator puts the right hand side into experssion context.

This means that function is then treated as the start of a function expression (which can be an IIFE) instead of a function declaration (which would throw an error if you tried to treat it as an IIFE, which this code does by following it with (3, 4)).

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335