javascriptecmascript-2020

Difference between ?? and ||


I was going through the new proposed functionalities in ES2020 and I stumbled upon the ?? operator also known as the “nullish coalescing operator”.

The explanation was vague and I still don't get how it is different from the logical OR operator (||)


Solution

  • Explanation is very simple lets assume that we have next situation, we want to get a value if it exist in object or use other value if it's undefined or null

    const obj = { a: 0 }; 
    const a = obj.a || 10; // gives us 10
    
    // if we will use ?? operator situation will be different
    const obj = { a: 0 };
    const a = obj.a ?? 10; // gives us 0
    
    // you can achieve this using this way
    const obj = { a: 0 };
    const a = obj.a === undefined ? 10 : obj.a; // gives us 0
    
    // it also work in case of null
    const obj = { a: 0, b: null };
    const b = obj.b ?? 10; // gives us 10
    

    Basically this operator does next:

    // I assume that we have value and different_value variables
    const a = (value === null || value === undefined) ? different_value : value;
    

    More information about this you can find in MDN web docs