[Solved-4 Solutions] “null coalescing” operator in JavaScript - JavaScript Tutorial



Problem:

Is there a “null coalescing” operator in JavaScript ?

Solution 1:

  • In C# the “null coalescing” operator is ?? operator, but JavaScript has an operator like this, i.e. ||.
  • The operator || is the logical OR operator. If any of the two operands are non-zero, then the condition becomes true. Here we can use the operator || with var in JavaScript:
  • Here the following example is given below,
var a = 0;
var b = null;
var c = a || b || 5;
console.log(c); // It will log 5
  • We can see the operation went till the right-most operand since the previous ones were always coerced into false. The returned value is not true but the value it self. In this case 5.

So we can try this one,

var a = 0;
var b = null;
var c = 5;

if (a || b || c) {
    console.log("This will be printed");
}
  • We know that the operation inside the if clause went till the right-most operand and since this operand was coerced into true the console will log the message.
if (5) 
{
    console.log("This will be printed");
}

Then 5 is implicitly coerced to true, the code enters the if clause.

Solution 2:

The JavaScript equivalent of the C# null coalescing operator (??) is using a logical OR (||):

var x = someString || "Cookies!";

Regardless of the type of the first operand, if casting it to a Boolean results in false, the assignment will use the second operand. Beware of all the cases below:

alert(Boolean(null)); // false
alert(Boolean(undefined)); // false
alert(Boolean(0)); // false
alert(Boolean("")); // false
alert(Boolean("false")); // true -- gotcha! :)

This means:

var x = null || new ShinyObject(); // is a new shiny object
var x = undefined || "well defined"; // is "well defined"
var x = 0 || 42; // is 42
var x = "" || "a million bucks"; // is "a million bucks"
var x = "false" || "no way"; // is "false"

Solution 3:

function coalesce() 
{
    var len = arguments.length;
    for (var i=0; i<len; i++) 
    {
        if (arguments[i] !== null && arguments[i] !== undefined) 
        {
            return arguments[i];
        }
    }
    return null;
}

var abc = {};
abc.val = coalesce(null, undefined, abc.val, 5);

// abc.val now contains 5

Solution 4:

function coalesce() 
{
    var i, undefined, arg;

    for( i=0; i < arguments.length; i++ ) 
    {
        arg = arguments[i];
        if( arg !== null && arg !== undefined
            && (typeof arg !== 'number' || arg.toString() !== 'NaN') ) 
        {
            return arg;
        }
    }
    return null;
}

Related Searches to javascript tutorial - “null coalescing” operator in JavaScript