The Confusing Comma In JavaScript |
Written by Ian Elliot | ||||
Thursday, 13 June 2019 | ||||
Page 3 of 3
Relationship To Active LogicThe comma operator can be thought of as being a member of the same family as &&, || and ? If you need to brush up on these operators see Javascript Jems - Active Logic, Truthy and Falsey. To summarize:
evaluates expressionA - if truthy then this is the result, otherwise the righthand expression is evaluated and is the result.
evaluates expressionA - if falsey then this is the result, otherwise the righthand expression is evaluated and is the result.
evaluates expressionA - if truthy it evaluates expressionB as the result and otherwise it evaluates expressionC as the result. The comma operator:
evaluates expressionA then the righthand expression is evaluated and is the result. It is also worth noting that the comma operator works well with any of the other active logic operators. In particular, the the ternary operator ? can often make use of it. For example:
If you assume that triesLeft is a counter of how many attempts the user has then you can decrement it and call the try function or call a function that informs the user that they have failed and then stops the program. ConclusionThe situation is best summed up as "you need to understand the comma, but you probably don't need to use it". What really matters is that you don't confuse the many other uses of the comma with the comma operator.
Now available as a book from your local Amazon.JavaScript Jems:
|
||||
Last Updated ( Thursday, 13 June 2019 ) |