What is the point of wrapping JavaScript statements in parentheses?

旧街凉风 提交于 2019-11-27 07:18:11

问题


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?


回答1:


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:

  • http://www.ecma-international.org/ecma-262/5.1/#sec-11.14
  • https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Comma_Operator


来源:https://stackoverflow.com/questions/16282879/what-is-the-point-of-wrapping-javascript-statements-in-parentheses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!