javascriptlogical-ornullish-coalescing

Difference between || and ?? operators


What is the difference between ?? and || in JS

const a = {}

const b = a.name ?? 'varun 1'

console.log(b)

const d = a.name || 'varun 2'

console.log(d)

In the above code they both work the same. I know || is OR i.e if the first statement is false then set the value for the next one. Is it same for ???


Solution

  • The main difference is that nullish coalescing(??) operator will only give the result as the right operand only if the left operand is either null or undefined.

    Whereas the OR(||) operator will give the result as right operand for all the falsy values of the left operand.

    Below are some examples

    const a = 0;
    // a || 10 --> Will result in 10, as || operator considers 0 as falsy value and resulting the right side operand
    console.log(`a || 10 = ${a || 10}`);
    // a ?? 10 --> Will result in 0, as ?? operator considers 0 as truthy value and resulting the left side operand
    console.log(`a ?? 10 = ${a ?? 10}`);

    const a = ''
    console.log(`a || "ABC" = ${a || "ABC"}`); // ABC
    console.log(`a ?? "ABC" = ${a ?? "ABC"}`); // ''

    const a = null;
    console.log(`a || 10 = ${a || 10}`); // 10
    console.log(`a ?? 10 = ${a ?? 10}`); // 10

    const a = {}
    // Here a.name will be undefined, hence both of the operands results the right side operand
    console.log(`a.name ?? 'varun 1' = ${a.name ?? 'varun 1'}`); // 'varun 1'
    console.log(`a.name || 'varun 2' = ${a.name || 'varun 2'}`); // 'varun 2'

    const a = {name: ''}
    // Here a.name will be '', then
    
    // ?? will result ''
    console.log(`a.name ?? 'varun 1' = ${a.name ?? 'varun 1'}`);
    // || will result in 'varun 2'
    console.log(`a.name || 'varun 2' = ${a.name || 'varun 2'}`);

    const a = false;
    console.log(`a || 10 = ${a || 10}`); // 10
    console.log(`a ?? 10 = ${a ?? 10}`); // false

    As mentioned above, both the operators behave similarly when the input is either null or undefined. The real difference we'll get to see when we provide falsy values such as 0, '', false, NaN.