JavaScript Nullish Coalescing & Logical OR

๐Ÿ“˜ Introduction

The Nullish Coalescing Operator (??) and the Logical OR Operator (||) are used to provide default values when a variable is null, undefined, or falsy.

๐Ÿ”น Nullish Coalescing Operator (??)

Returns the right-hand value if the left-hand value is null or undefined.

let user;
let name = user ?? 'Guest';
console.log(name); // 'Guest'
            

๐Ÿ”น Logical OR Operator (||)

Returns the right-hand value if the left-hand value is falsy (0, '', null, undefined, false, NaN).

let user = '';
let name = user || 'Guest';
console.log(name); // 'Guest'
            
โš ๏ธ OR treats 0, false, and '' as falsy, while Nullish Coalescing only treats null and undefined as nullish.

๐Ÿงช Try It Yourself

Click the button to see Nullish Coalescing and Logical OR in action: