The `??` Operator ( Nullish coalescing operator ) in javaScript

The `??` Operator ( Nullish coalescing operator ) in javaScript

Let's learn Js, until AI takes over.

With the help of ??
height = height ?? 100;

Without ??
height = (height !== undefined && height !== null) ? height : 100;

Yes, The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

Syntax :

leftExpr ?? rightExpr

Some Examples from the MDN Docs :

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

const baz = 0 ?? 42;
console.log(baz);
// expected output: 0
const nullValue = null;
const emptyText = ""; // falsy
const someNumber = 42;

const valA = nullValue ?? "default for A";
const valB = emptyText ?? "default for B";
const valC = someNumber ?? 0;

console.log(valA); // "default for A"
console.log(valB); // "" (as the empty string is not null or undefined)
console.log(valC); // 42

Note :

  • Like the OR and AND logical operators, the right-hand side expression is not evaluated if the left-hand side proves to be neither null nor undefined.
    function A() { console.log('A was called'); return undefined;}
    function B() { console.log('B was called'); return false;}
    function C() { console.log('C was called'); return "foo";}
    console.log( A() ?? C() );
    // logs "A was called" then "C was called" and then "foo"
    // as A() returned undefined so both expressions are evaluated
    console.log( B() ?? C() );
    // logs "B was called" then "false"
    // as B() returned false (and not null or undefined), the right
    // hand side expression was not evaluated
    
  • It is not possible to combine both the AND (&&) and OR operators (||) directly with ??. A SyntaxError will be thrown in such cases.
    null || undefined ?? "foo"; // raises a SyntaxError
    true || undefined ?? "foo"; // raises a SyntaxError
    
    (null || undefined) ?? "foo"; // returns "foo"
    
  • The nullish coalescing operator treats undefined and null as specific values and so does the optional chaining operator (?.) which is useful to access a property of an object which may be null or undefined.
    let foo = { someFooProp: "hi" };
    console.log(foo.someFooProp?.toUpperCase() ?? "not available"); // "HI"
    console.log(foo.someBarProp?.toUpperCase() ?? "not available"); // "not available"
    

Follow me to learn about new Js related stuffs on a regular basis.

reference:

Did you find this article valuable?

Support De-mystify Tech by becoming a sponsor. Any amount is appreciated!