Absolutely, it's valid and functions smoothly in Chrome:
var x, y, z;
x = 6;
y = 7;
z = x !== y ? (x = 1, y = 2) : (x = 2, y = 1);
console.log("x = " + x);
console.log("y = " + y);
console.log("z = " + z);
I do acknowledge that the code may not be easily readable for humans. :-) It seems like a result of minification, as jamietre mentioned in the comments.
The comma operator is a binary operator that evaluates its operands sequentially from left to right, discarding the results of each operand except the last one. The conditional operator (ternary operator), on the other hand, selects one of two sub-expressions based on a condition.
In this case, there are a total of seven* different expressions nested within the ternary operation, resulting in either a value of 2 or 1 based on the initial comparison between x
and y
, along with assigning values to x
and y
.
Using the comma operator for side effects can make the code less maintainable. It's crucial to consider whether using the comma operator adds any substantial benefits when the left-hand operand doesn't have significant side effects.
* Yes, seven separate expressions within the overall ternary operation:
x !== y
- the first comma expression
x = 1
y = 2
- the second comma expression
x = 2
y = 1
Regarding your edit containing the updated statement, that also works effectively:
function evaluate(num) {
var b = 7,
d = 1,
e = 2,
f = 3,
g = 4,
h = 5,
i = 6;
num !== 0 ? b < 0 ? (h = b / num, e = h - 1, f = -2 * b + 2 * num * e, i = -2 * b + 2 * num * h, d = 2 * h * num - 2 * b - 2 * num) : (h = b / num, e = h + 1, f = 2 * b - 2 * num * e, i = -2 * b + 2 * num * h, d = -2 * h * num + 2 * b) : d = h = e = f = i = 0;
console.log("num = " + num);
console.log("b = " + b);
console.log("d = " + d);
console.log("e = " + e);
console.log("f = " + f);
console.log("g = " + g);
console.log("h = " + h);
console.log("i = " + i);
}
evaluate(0);
evaluate(1);
.as-console-wrapper {
max-height: 100% !important;
}
However, I sincerely hope this code is minified because if someone wrote it in this form, they must have a strong aversion towards future maintenance efforts... ;-)