/

A Curious Usage of Commas in JavaScript

A Curious Usage of Commas in JavaScript

In the realm of JavaScript, I recently stumbled upon something intriguing and potentially beneficial: the comma operator. While I commonly use commas to separate properties within an object or items within an array, I had never paid much attention to its application within expressions.

Let’s consider the following example:

1
('a', 'b')

In this scenario, both expressions (in this case, strings) are evaluated, and the result is the last element, which is the expression following the final comma. In this particular instance, it returns the value 'b'.

To make use of this behavior, you can assign the value to a variable, as shown below:

1
2
const letter = ('a', 'b')
letter === 'b' // true

By leveraging this comma operator, you can achieve concise and efficient code. It’s certainly an interesting construct to explore in JavaScript.

tags: [“JavaScript”, “commas”, “expressions”, “comma operator”, “variable assignment”]