7

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?

Community
  • 1
  • 1
Shawn Mclean
  • 56,733
  • 95
  • 279
  • 406

1 Answers1

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 ;
Sampson
  • 265,109
  • 74
  • 539
  • 565
  • 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... –  May 28 '12 at 04:34
  • @Lolcoder A boolean `false` is an actual false. *Falsy* values would be things like the number `0`, or an empty string. – Sampson May 28 '12 at 04:38
  • 1
    @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. – nnnnnn May 28 '12 at 04:49