Nullish Coalescing (??)

Nullish Coalescing (??)

In this blog, we will learn about JavaScipt's Nullish Coalescing operator, which is denoted by the double question mark (??). It was introduced in ECMA script's 11th edition (popularly known as ES11).

Introduction:

Nullish Coalescing (??)

It is a logical operator that takes 2 values as input and it returns the output.

first_value ?? second_value

here the operator ?? will return the second_value when first_value will be either null or undefined and otherwise, it will return first_value.

const foo = null ?? 'default string';
console.log(foo);
//"default string"

We will discuss this topic in 3 parts:

  • The What part

  • The How part

  • The Why part

What is Nullish Coalescing? (The What Part)

It is the logical operator of JavaScipt also known as the short-circuiting operator which means the evaluation of a logical operation exits in between even before complete evaluation.

The Logical OR || and AND && operators are short-circuiting operator, for example:

let a = false;
let b = true;
console.log(a && b);
// false
// In case of Logical AND value of 'a' is false, so the final expression will be false only irrespective of the further condition(s) and hence it logs false.
console.log(b && a);
//false
//In this case AND operator will first check value of 'b' which is true but the expression will get evaluated untill we get first falsy condition.

console.log(a || b);
//true
// In case of Logical OR value of 'a' is false but it will further evaluate the expression untill we get first truthy condition.
console.log(b || a);
//true
// In this case OR operator will first check value of 'b' which is true, so the final expression will be true only irrespective of the further condition(s) and hence it logs true.

In the above example, an expression with && will be true only if all the operands are true otherwise false. Similarly with || the expression will be false only if all the operands are false otherwise true.

Like the OR and AND logical operators, in the case of Nullish Coalescing ?? operator the right-hand side expression is not evaluated if the left-hand side proves to be neither null nor undefined.

const a = null;
const b = 55;
console.log(a ?? b);
// 55

How to use Nullish Coalescing? (The How part)

Basically, in this part, we will discuss different scenarios with the code using ?? operator.

let a = "first string";
let b = "second string";
console.log(a ?? b);
// first string

let c;
let d = "some value";
console.log(c ?? d);
// some value

in the first example, we did see both the variables a & b have string values so ?? is returning the left-hand side value whereas, in the second example, the only variable d has string value namely some value and variable c is undefined so the output is some value.

we can also use a sequence ?? to choose the first value which is not null/undefined. Let's say we have user's data in variables firstName, middleName, lastName. All of them may be not defined if the user decided not to fill in the corresponding values.

We’d like to display the user name using one of these variables or show “data not available” if all of them are null/undefined.

const firstName = null;
const middleName = null;
const lastName = undefined;
console.log(firstName ?? middleName ?? lastName ?? "data not available")
// "data not available"

Logical OR (||) and Nullish Coalescing (??)

We can use ?? with || by providing proper parenthesis otherwise, it will raise a syntax error.

console.log(null || undefined ?? "some string");
//SyntaxError: Unexpected token '??'
console.log((null || undefined) ?? "some string");
// "some string"

the above example is valid for logical AND && as well.

  • Comparison between || and ??

    The || returns the first truthy value of logical expression whereas the ?? returns the first defined value.

      let height = 0;
    
      console.log(height || 100);
      // 100
      console.log(height ?? 100);
      // 0
    
  • In JavaScipt there are total 6 falsy values:

  • undefined

  • null

  • NaN

  • 0

  • false

  • "" (empty string)

so if any of these falsy values have been used in any logical expression where the operator is || it will consider these values as falsy only, whereas in the case of ?? it will consider the falsy value to null/undefined only.

Why use Nullish Coalescing? (The Why part)

So far we have seen that the ?? operator returns the right-hand side value if the left-hand side value is null/undefined and the same output we will get if we use || but sometimes we need "" (empty strings), 0 and if we use || then we have to write additional codes for example:

const firstName = "Shreyansh";
let middleName;
const lastName = "Faye";
if(middleName === undefined || middleName === null) {
    middleName = "";
}
const user = {
    Name: firstName,
    middlename: middleName,
    surname: lastName
};
console.log(user);

In the above code example if a user's middle name is not present so to get the user data without the middle name we wrote an if condition, these extra lines of code can be avoided if we would have used ??.

const firstName = "Shreyansh";
let middleName;
const lastName = "Faye";
middleName = middleName ?? "";
const user = {
    Name: firstName,
    middlename: middleName,
    surname: lastName
};
console.log(user);

So to avoid writing extra lines of code and checks to confirm that the variable gets the value which could be 0 or "" (empty string) other than the null/undefined we use the Nullish Coalescing operator (??).

Conclusion

  • The Nullish coalescing operator returns the right-hand side value if the left-hand side value is null/undefined.

  • It is a logical operator/short-circuiting operator, which means if the left operand is null/undefined then without even a complete evaluation, the expression will return the right side operand.

  • A SyntaxError will occur if you combine the logical AND or OR operator directly with the Nullish Coalescing operator. We need to use proper parentheses to avoid this error.

  • Sometimes we want the right side of the operand to be evaluated only if the left side of the operand is null/undefined. So to avoid extra checks because of the falsy value we use the Nullish Coalescing operator.