comma operator (,)
In JavaScript, the comma operator (,) evaluates each of its operands from left to right and returns the value of the last one. The values of the earlier operands are discarded, so they matter only for their side effects, such as an assignment or a function call.
The comma operator has the lowest precedence of all JavaScript operators, lower even than the assignment operators. A comma expression inside a larger expression usually needs parentheses. Most commas in JavaScript code aren’t this operator at all. Commas in array literals, object literals, parameter lists, function arguments, and let or const declarations are separators.
JavaScript Comma Operator Syntax
A comma expression joins two or more expressions:
<expr1>, <expr2>[, <exprN> ...]
The whole expression evaluates to the value of the last operand.
JavaScript Comma Operator Examples
Say a function checks whether a word is a palindrome by moving one index forward from the start and another backward from the end. The update clause of a for loop uses the comma operator to change both indexes:
> function isPalindrome(word) {
… for (let i = 0, j = word.length - 1; i < j; i++, j--) {
… if (word[i] !== word[j]) return false;
… }
… return true;
… }
undefined
> isPalindrome("level")
true
> isPalindrome("lever")
false
Only i++, j-- is the comma operator here. The comma in let i = 0, j = word.length - 1 separates two declarations.
A concise arrow function body can count calls and still return a value:
> let calls = 0;
undefined
> [3, 5, 8].map((n) => (calls++, n * 2))
[ 6, 10, 16 ]
> calls
3
The callback increments calls and returns n * 2.
Leaving out the parentheses changes the meaning, because assignment binds tighter than the comma:
> let total;
undefined
> total = (1, 2)
2
> total = 1, 2
2
> total
1
Without parentheses, total = 1, 2 assigns 1 to total and then evaluates 2 as the result of the whole expression.
JavaScript Comma Operator Gotchas
- A comma expression returns a value, not a property reference, so
(0, user.greet)()calls the method withthisset toundefinedin strict mode and toglobalThisin sloppy mode. - A stray comma in a
returnstatement, such asreturn a, b, evaluatesa, discards its value, and returns onlybwithout an error. - A comma between two arguments passes two arguments. Only a comma expression in its own parentheses, such as
log((first, second)), passes its result as one argument.
JavaScript Comma Operator Use Cases
- Updating two loop variables in the update clause of a
forloop - Running a side effect before returning a value from a concise arrow function body
- Calling
eval()indirectly with(0, eval)(code) - Detaching a method from its object to call it without its
thisvalue
Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.
By Leodanis Pozo Ramos • Updated Nov. 12, 2026