9

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.

some_bloody_fool
  • 4,605
  • 14
  • 37
  • 46
  • possible duplicate of [null coalescing operator for javascript?](http://stackoverflow.com/questions/476436/null-coalescing-operator-for-javascript) – l0b0 Apr 24 '12 at 13:23

4 Answers4

11

You can use an OR.

 var someVar = null || value;
 var otherVar = null || variableThatEvaluatesToNull || functionThatEvaluatesToNull() || value;
pete
  • 24,141
  • 4
  • 37
  • 51
5

The problem with || are values like 0, which may be desired. You could 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
}

Which you could then call as expected:

var myNonNullValue = Coalesce(null, objectA, objectB, "defaultValue");
nybbler
  • 4,793
  • 28
  • 23
3

You can use "falsy" values and the || operator (logical OR):

var foo = bar || baz;

Above would assign the value of bar to foo if bar evaluates to a "truthy" value and baz otherwise (e.g. if bar is undefined, null, false etc.).

BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
-1

Here's a link to basically the same question: Is there a "null coalescing" operator in JavaScript?

That's call null coalescing. In C#, there's a null coalesce operator "??" and that's what the original asker of the linked question was referring to.

Community
  • 1
  • 1
D. Patrick
  • 2,894
  • 26
  • 37