Maximus Maximus - 5 months ago 26
Javascript Question

Rewriting `c > 3 && r && Object.defineProperty(target, key, r), r` into "normal" presentation

I have the following:

return c > 3 && r && Object.defineProperty(target, key, r), r;

I've rewritten it like that:

if (c > 3 && r) {
Object.defineProperty(target, key, r);

return r;

Have I got it right?


Yes, those are equivalent. You caught both potential problems: the && returning an operand and the , skipping that return value.

As you can see (for the x, y) part, the value of the first operand is disregarded. The comma operator simply evaluates the first expression, it doesn't care what happens (unless an exception is thrown). For example:

console.log((true && false, 3));

The && operator will evaluated the first operand and short-circuit if it was false, otherwise evaluating the second operand and returning its result. That means the Object.defineProperty only runs if c > 3 && r, which you captured. While the , operator then discards the result, defineProperty has already mutated the object.