6

Possible Duplicate:
null coalescing operator for javascript?

In C#, you can do this:

var obj = newObject ?? defaultObject;

That says assign newObject to obj if not null else assign defaultObject. How do I write this in javascript?

1

1 Answer 1

6

While it's considered an abusage, you can do the following:

var obj = newObject || defaultObject;

Note that if newObject is of any falsy value (such as 0 or an empty string), defaultObject will be returned as the value of obj. With this in mind, it may be preferred to use either the ternary operator or a standard if-statement.

var obj = ( "undefined" === typeof defaultObject ) ? defaultObject : newObject ;
Sign up to request clarification or add additional context in comments.

3 Comments

This is slightly different though, as it will result in defaultObject for any false-y value of newObject. That is, there is no "direct"-equivalent, so the ternary (??) with an explicit equality might capture a given intent better...
@Lolcoder A boolean false is an actual false. Falsy values would be things like the number 0, or an empty string.
@pst - While I agree with you, I would note that if you know in advance that defaultObject actually is an object then it will never be falsy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.