I have discovered that wrapping different statements in parentheses will return the last one:
(34892,47691876297,2000) => 2000
('test',73,document.createElement('p')) => <p></p>
And I also found out that all the statements are executed anyway:
(console.log('test'), console.log('test2'), console.log('test3'), 6)
Will log:
test
test2
test3
And the result will be 6.
However, I've also found that some statements can't be used:
(throw new Error(), 10) => SyntaxError: Unexpected token throw
(if (1) console.log('test'), 5) => SyntaxError: Unexpected token if
So, what is the point of this parenthesis-comma notation? You could easily execute all the statements and then use the last statement's value. What is this for? Am I using it incorrectly?
That is the comma operator :)
It lets you evaluate expressions from left to right, returning the last operand's result (which, in your case, isn't stored anywhere, and is perfectly valid).
Reference:
The most obvious point of this is to allow for multiple expressions in a for loop:
for (let x=3, y=6; x < 10; x++, y++) {...}
^^^^^^^^
That's the comma operator, the same operator that also allows for the examples you provided
return (x, y)
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