Javascript null conditional expression

Possible duplicate:
null coalescence operator for javascript?

In C # you can do this:

var obj = newObject ?? defaultObject; 

This means that the assignment of newObject is obj , if not null yet assign defaultObject . How to write this in javascript?

+6
source share
1 answer

While it is considered abuse, you can do the following:

 var obj = newObject || defaultObject; 

Note that if newObject has any falsy value (for example, 0 or an empty string), defaultObject will be returned as obj value. With this in mind, it may be preferable to use either the ternary operator or the standard if statement.

 var obj = ( "undefined" === typeof defaultObject ) ? defaultObject : newObject ; 
+6
source

Source: https://habr.com/ru/post/916815/


All Articles