If left side is undefined or null then return right side
let user = null;console.log(user ?? "Anonymous"); // Anonymous
Comparison with OR operator ||
Using OR operator is similar but working is different and could result in different behavior
If left side is false then return right side
let price = 0;console.log(price ?? 100); // 0 since price is not undefined or nullconsole.log(price || 100); // 100 since price is 0 hence evaluated to false
Nullish Coalescing Assignment
Nodejs v14 does not support it, Node v16 support it
let user;user ??= "Anonymous"; // assign Anonymousconsole.log(user); // Anonymous
Optional Chaining ?.
It stops evaluation if left side is undefined or null and returns undefined
let user = {};console.log(user?.address?.street); // undefined
More variants: ?.() and ?.[]
let dog = { name: 'Tommy', barks: function() { console.log('dog barks'); }};dog.barks?.(); // dog barksconsole.log(dog?.['name']); // Tommy
Combine optional chaining with null coalescing
We can use optional chaining and define a default value using null coalescing
let user = { address: {}};console.log(user?.address?.street ?? 'MG marg'); // MG marg