DEV Community

Cover image for The JavaScript Comma Operator
Anthony Oyathelemhi
Anthony Oyathelemhi

Posted on

The JavaScript Comma Operator

Comma(,) in JavaScript is mostly used to 'join' other things, like values and expressions. In this usage, the ECMAScript specification refers to it as an Elision. Some examples of this usage include, defining/passing multiple arguments to a function, adding items to arrays/objects, and 'one line' variable declarations

code snippet showing comma usage in JavaScript

Like other symbols in JavaScript, it has another use, as an operator. When used in an expression, it returns the right-most value (or the value of the last expression in the sequence)

Let's test this out. Type the following into your browser console or any JavaScript runtime environment

var two = 2

two++, two
// 3
Enter fullscreen mode Exit fullscreen mode

You should see 3 returned in the terminal. No surprises there since the compound expression is read from left to right, and all individual expressions will be evaluated before returning the value of the final expression

It's hard to imagine where this could really be useful other than writing shorter lines of code, which could be hard to understand for some people

If you can think of some clever use of the Comma operator, please let me know in the comments

References and More Reading

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator
https://tc39.es/ecma262/multipage/ecmascript-language-expressions.html#prod-Elision

Top comments (2)

Collapse
 
smlka profile image
Andrey Smolko

Hey=) there is my typical and dummy use of comma operator:

```const f = ()=>(value)
// wanna console.log value
const f = ()=>(console.log(value), value)



as you said comma execute all expressions and return top-right in the line
Enter fullscreen mode Exit fullscreen mode
Collapse
 
frontendtony profile image
Anthony Oyathelemhi

Clever