DEV Community

Cover image for The JavaScript Comma Operator
Anthony Oyathelemhi
Anthony Oyathelemhi

Posted on

3 1

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️