Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mimick the functionality of the SQL Coalesce statement in Javascript

I was wondering if there is a way in javascript to have logic similar to the coalesce statement in sql which will return data in a specified order like this:

Select top 1 Coalesce(ColA, ColB, "No Data Found") from TableA;

is there an elegant way to deal with null values in Javascript, the same way that sql returns results in the above statement?

i know i could technically have a switch statement, but this would require some possibly unnecessary code

Thank you.

like image 322
some_bloody_fool Avatar asked Feb 02 '12 21:02

some_bloody_fool


People also ask

Does JavaScript have coalescing operator?

JavaScript made sure this can be handled with its nullish operator also known as the Null Coalescing Operator, which was added to the language with ECMAScript 2020. With it, you can either return a value or assign it to some other value, depending on a boolean expression.

How do you use coalesce in SQL query?

The SQL server's Coalesce function is used to handle the Null values. The null values are replaced with user-defined values during the expression evaluation process. This function evaluates arguments in a particular order from the provided arguments list and always returns the first non-null value.

What are the syntax and use of the coalesce function?

The COALESCE function returns the first non-NULL value from a series of expressions. The expressions are evaluated in the order in which they are specified, and the result of the function is the first value that is not null. The result of the COALESCE function returns NULL only if all the arguments are null.


1 Answers

You can use an OR.

 var someVar = null || value;
 var otherVar = null || variableThatEvaluatesToNull || functionThatEvaluatesToNull() || value;
like image 86
pete Avatar answered Oct 21 '22 03:10

pete