The Confusing Comma In JavaScript
Written by Ian Elliot   
Thursday, 13 June 2019
Article Index
The Confusing Comma In JavaScript
This Is Not The Comma You Are Looking For
Active Logic

Relationship To Active Logic

The 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:

expressionA || expressionB

evaluates expressionA - if truthy then this is the result, otherwise the righthand expression is evaluated and is the result.

expressionA && expressionB

evaluates expressionA - if falsey then this is the result, otherwise the righthand expression is evaluated and is the result.

expressionA ? expressionB:expressionC

evaluates expressionA - if truthy it evaluates expressionB as the result and otherwise it evaluates expressionC as the result. 

The comma operator:

expressionA , expressionB

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:

triesLeft ? (triesLeft--,try()):(noMoreTries(),Finish());

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. 

Conclusion

The 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.

comma

 

 

Now available as a book from your local Amazon.

JavaScript Jems:
The Amazing Parts

kindlecover

JavaScript Jems - Functional And Not Quite Functional

Original drafts of chapters.

Contents

  1. JavaScript Patterns 
    Why JavaScript is a Jem
  2. Objects with Values in JavaScript*
  3. Private Functions In JavaScript
  4. Chaining - Fluent Interfaces In JavaScript*
  5. Active Logic, Truthy and Falsey*
  6. The Confusing Comma In JavaScript*
  7. Self Modifying Code*
  8. Lambda expressions
  9. Meta Programming Using Proxy
  10. Master JavaScript Regular Expressions
  11. The Function Approach To Programming

<ASIN:1871962579>

<ASIN:1871962560>

<ASIN:1871962501>

<ASIN:1871962528>

espbook

 

Comments




or email your comment to: comments@i-programmer.info

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

 

 



Last Updated ( Thursday, 13 June 2019 )