0

I saw this piece of code in a webpack compiled file

(1,2, function(x) {
    console.log(x);
    return 4;
})(5);

This seems to execute correctly. I am aware the 5 is a parameter to function(x)

I don't understand what the 1,2 are? How is this valid?

Sai Datta
  • 895
  • 1
  • 9
  • 25
  • 2
    It's the comma operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator. The comma operator evaluates everything joined by commas and returns the result of the last thing. So `1,2,3` results in `3`. Another example `'hello', [1,2,3], 100` results in 100. So `1,2, function () {}` results in a function. – slebetman Oct 14 '21 at 17:23
  • Also generally, see [what-does-this-symbol-mean-in-javascript](https://stackoverflow.com/questions/9549780/what-does-this-symbol-mean-in-javascript), and you can go to e.g. https://astexplorer.net/ and look at the resulting AST for how expressions are parsed. – ASDFGerte Oct 14 '21 at 18:03

1 Answers1

1

Well, it's because the brackets only returns the function

(thing1,thing2,thing3,thing4....,thingN) would show the last thing on the list(in this case, thingN)

Example

var bracketTest1=(1,3,5,7,9,null)
console.log(bracketTest1) //null
var bracketTest2=(null,1,2,3,4)
console.log(bracketTest2) //4
var bracketTest3=(null,1,2,4,5,function(x){return x})
console.log(bracketTest3) //function(x)
console.log(bracketTest3(Object)) //function Object()
console.log((1,2,3,4,null,undefined)) //prints undefined
The Bomb Squad
  • 4,192
  • 1
  • 9
  • 17