DEV Community

Keertivaas S
Keertivaas S

Posted on

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

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"

Top comments (6)

Collapse
 
efpage profile image
Eckehard

Yea, it´s tricky. Thank you for your examples!

Collapse
 
justanordinaryperson profile image
Keertivaas S

Welcome :)

Collapse
 
durgeshsingh1 profile image
Durgesh Singh

Good 👍

Collapse
 
justanordinaryperson profile image
Keertivaas S

Thanks!

Collapse
 
p1k2i profile image
Николай Миронов

Performance?

Collapse
 
justanordinaryperson profile image
Keertivaas S

?? is a little costlier than || as it would be expanded when it is being Transpiled (Eg : Babel). However, for smaller conditions, ?? is good enough

dev.to/tusharshahi/cost-of-unneces... - Found this article good