?? (Nullish coalescing) vs || (Logical OR) in Javascript

Keertivaas S - Jun 16 - - Dev Community

Both Nullish Coalescing Operator (??) and Logical OR (||) operator are often used in JavaScript to provide a default value to variables. These help us prevent any unexpected behavior in our code.

Nullish Coalescing Operator (??): This is specifically designed to handle situations where the left operand might be unintentionally left unassigned (null) or missing a a value (undefined). It only considers null and undefined as nullish values.

Logical OR (||): This is useful when you want a default value if the left operand is any falsy value. This includes null, undefined, 0, empty string (""), false, and NaN.

Lets take these examples :

  1. If you want to check and avoid printing empty values, use the Logical OR Operator (||).

console.log("" || "Hello") // "Hello"
console.log("" ?? "Hello") // ""

  1. If 0 or Boolean false is a valid return value in your use-case, use ?? (Nullish coalescing).

console.log(0 || "Hello") // "Hello"
console.log(0 ?? "Hello") // 0

console.log(false || "Hello") // "Hello"
console.log(false ?? "Hello") // false

console.log(0 || "Hello") // "Hello"
console.log(0 ?? "Hello") // 0

  1. If you are only checking for undefined or null, you can go for either one of them :

console.log(undefined ?? "Hello") // "Hello"
console.log(undefined || "Hello") // "Hello"

console.log(null ?? "Hello") // "Hello"
console.log(null || "Hello") // "Hello"

. . . . . .