18

Is there any equivalent of ?? operator as exists in C# in JavaScript to defeat 'undefined' checking? For example:

var count = something ?? 0;
Hans
  • 2,674
  • 4
  • 25
  • 48

1 Answers1

28

Use logical OR

var count = something || 0;
Zee
  • 8,420
  • 5
  • 36
  • 58
  • 4
    Be aware this will not work with booleans : `someflag || true` will return true if `someflag` is false – tigrou Aug 18 '17 at 15:53
  • wouldn't this also fail with an int that is 0 ? – henon Mar 19 '18 at 12:52
  • Yes, this check will give you bad results with anything on the left side of the operand that could legitimately be falsy. Zero is the obvious problem here, but in this case won't matter. I have been bitten by this so many times i try to avoid using it for anything other than comparing objects now. – Morvael Jan 22 '19 at 09:20