-2

Do these two statements work the same?

var x = y ? y : 0;

var x = y || 0;

I have been using the first for a while, but if the second is the same, i would rather use that, as it is much shorter in a lot of cases (when y is a long variable name or statement, for example)

Russell Chisholm
  • 645
  • 9
  • 13
  • 1
    Did you read the docs on MDN? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR – epascarello Mar 01 '23 at 20:49
  • 2
    For the sake of clarity, I prefer explicitly checking if something is `null` or the particular false-y value to keep the types clear. For null coalescence, `??` does the job nowadays too, which is both clear and concise. – General Grievance Mar 01 '23 at 20:50
  • 2
    Don't focus on short code. Focus on readable code. If you want it to be short, you can always run it through a minifier. – Ivar Mar 01 '23 at 20:53
  • 1
    what is actually the question? in javascript both expression are equal. take for falsy value zero. – Nina Scholz Mar 01 '23 at 20:58
  • 1
    also [Can the ternary operator be equivalent to short circuiting with the logical operators?](https://stackoverflow.com/questions/35165166/can-the-ternary-operator-be-equivalent-to-short-circuiting-with-the-logical-oper) – pilchard Mar 01 '23 at 22:07

1 Answers1

1

The logical OR operator is a short-hand for the ternary operator when assigning a value.

As long as the value is truthy, it will not use the default (else).

The test below proves that they work similar:

const f1 = x => x ? x : 0, f2 = x => x || 0;
console.log(
  [undefined, null, NaN, Infinity, 0, 1, false, true, '', 'foo', function() {}]
    .every(x => f1(x) === f2(x)));
.as-console-wrapper { top: 0; max-height: 100% !important; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132