Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript null conditional expression [duplicate]

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?

like image 883
Shawn Mclean Avatar asked May 28 '12 04:05

Shawn Mclean


People also ask

Is there a null coalescing operator 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.

What is ?: In JavaScript?

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.

Does JavaScript have Elvis operator?

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.

Is coalesce null?

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.


1 Answers

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 ;
like image 163
Sampson Avatar answered Oct 09 '22 00:10

Sampson