How to match SQL Coalesce statement functionality in Javascript

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

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

Is there an elegant way to handle null values ​​in Javascript, just like sql returns the results in the above statement?

I know that I can technically have a switch statement, but this will require some kind of optional code

Thanks.

+8
javascript jquery coalesce
source share
4 answers

You can use OR.

  var someVar = null || value; var otherVar = null || variableThatEvaluatesToNull || functionThatEvaluatesToNull() || value; 
+10
source share

You can use the false value and the || (logical OR):

 var foo = bar || baz; 

Above, it will assign the value bar foo if bar is evaluated as the "right" value, and baz otherwise (for example, if bar is undefined, null, false, etc.).

+3
source share

Problem with || are values, such as 0 , that may be desirable. You can write your own javascript function to simulate COALESCE.

 function Coalesce() { var args = Coalesce.arguments; for (var i = 0; i < args.length; ++i) { if (null !== args[i]) return args[i]; } return null; // No non-null values found, return null } 

What could you name as expected:

 var myNonNullValue = Coalesce(null, objectA, objectB, "defaultValue"); 
+3
source share

Here is a link to the same question: Is there a β€œnull coalescing” operator in JavaScript?

This is a null coalescence call. In C #, there is a null coalescing operator "??" and what the original questionnaire related question referred to.

-one
source share

All Articles