Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

comma - What is the point of wrapping JavaScript statements in parentheses?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...