What’s the difference between || and ?? in JavaScript?
19 November 2023 (Updated 19 November 2023)
On this page
Logical OR (||)
|| returns the first operand if it’s truthy; otherwise, it returns the second. It will consider any falsy values like 0 or "" as a reason to fall back to the second operand:
console.log(0 || "default") // Output: "default" since 0 is falsy
console.log("" || "default") // Output: "default" since "" is falsy
console.log(1 || "default") // Output: 1 since 1 is not falsy
Null Coalescing Operator (??)
The ?? operator was introduced in ES2020 to help you fall to a default value when dealing with “nullish” values like null or undefined. It doesn’t consider falsy values like 0 or "" as nullish and so a reason to fallback to the second operand.
console.log(0 ?? "default") // Output: "0" since 0 is not null or undefined
console.log("" ?? "default") // Output: "0" since "" is not null or undefined
let name = null
console.log(name ?? "default") // Output: "default" since name is null
Tagged:
JavaScript
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment