Example 1 — Side Effect then Value
Log something, then return a number.
const n = (console.log("ready"), 7);
console.log(n); How It Works
- Log first. The first expression prints.
- Return last. The assignment receives
7.
The comma operator (,) evaluates expressions from left to right and returns the value of the last one.
const result = (console.log("first"), console.log("second"), 42);
console.log(result); 42.Log something, then return a number.
const n = (console.log("ready"), 7);
console.log(n); 7.Update two variables in the increment clause.
let out = "";
for (let i = 0, j = 3; i < 3; i++, j--) {
out += i + ":" + j + " ";
}
console.log(out.trim()); i++ and j-- both run each iteration.i reaches 3.Do a bit of work, then return a value from a function.
function nextId(box) {
return (box.n += 1, box.n);
}
const box = { n: 10 };
console.log(nextId(box));
console.log(box.n); box.n += 1 runs first.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
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful