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?
The nullish coalescing operator ( ?? ) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined , and otherwise returns its left-hand side operand.
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
JavaScript now has equivalents for both the Elvis Operator and the Safe Navigation Operator. The optional chaining operator ( ?. ) is currently a stage 4 ECMAScript proposal. You can use it today with Babel.
The COALESCE function returns NULL if all arguments are NULL . The following statement returns 1 because 1 is the first non-NULL argument. The following statement returns Not NULL because it is the first string argument that does not evaluate to NULL . you will get the division by zero error.
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 ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With