JavaScript Comma Operator

Beginner
6 min read
Updated: Nov 2026
3 examples

Definition and Usage

The comma operator (,) evaluates expressions from left to right and returns the value of the last one.

JavaScript Syntax

JavaScript
const result = (console.log("first"), console.log("second"), 42);
console.log(result);
Try it Editor

How It Works

  1. Left to right. Each expression runs in order for its side effects.
  2. Last wins. The whole parenthesized expression yields the final value—42.
  3. Parentheses help. Use parentheses so the comma is not confused with argument lists.

Examples

Example 1 — Side Effect then Value

Log something, then return a number.

JavaScript
const n = (console.log("ready"), 7);
console.log(n);
Try it Editor

How It Works

  1. Log first. The first expression prints.
  2. Return last. The assignment receives 7.

Example 2 — Comma in a for Loop

Update two variables in the increment clause.

JavaScript
let out = "";
for (let i = 0, j = 3; i < 3; i++, j--) {
  out += i + ":" + j + " ";
}
console.log(out.trim());
Try it Editor

How It Works

  1. Two counters. i++ and j-- both run each iteration.
  2. Build string. Pairs print until i reaches 3.

Example 3 — Return After Work

Do a bit of work, then return a value from a function.

JavaScript
function nextId(box) {
  return (box.n += 1, box.n);
}
const box = { n: 10 };
console.log(nextId(box));
console.log(box.n);
Try it Editor

How It Works

  1. Increment. box.n += 1 runs first.
  2. Return new value. The comma expression returns the updated number.

Frequently Asked Questions

The value of the rightmost expression after evaluating all expressions left to right.

No. Commas in [1, 2] or fn(a, b) separate items or arguments; the operator is a distinct expression form.

Sparingly. Prefer clear statements. It is handy in for increments or dense one-liners.

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful