20

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

var count = something ?? 0;
3
  • 3
    var count = (typeof something === 'undefined') ? 0 : something; This is a more verbose version of @Zee's answer (arguably more secure). Commented May 22, 2015 at 10:15
  • @evolutionxbox: I think you have the values the wrong way around Commented May 22, 2015 at 10:18
  • @musefan you're right, I did. Commented May 22, 2015 at 10:19

1 Answer 1

28

Use logical OR

var count = something || 0;
Sign up to request clarification or add additional context in comments.

3 Comments

Be aware this will not work with booleans : someflag || true will return true if someflag is false
wouldn't this also fail with an int that is 0 ?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.