🔥 Quick Tip: What's the benefit of using - Nullish Coalescing operator
Helder Burato Berto
Posted on June 9, 2020
On this simple trick, I'll show you the benefit of using Nullish Coalescing - ??
instead of OR - ||
.
const user = {
name: '',
isDev: undefined,
isHuman: false,
age: 0,
};
// Using ?? operator
console.log(user.name ?? 'John Doe'); // => ''
console.log(user.isDev ?? false); // => false
console.log(user.isHuman ?? true); // => false
console.log(user.age ?? 20); // => 0
// ----
// Using || operator
console.log(user.name || 'John Doe'); // => 'John Doe'
console.log(user.isDev || false); // => false
console.log(user.isHuman || true); // => true
console.log(user.age || 20); // => 20
Notice in some cases with different values from null
or undefined
the operator ||
isn't get a wanted value.
Note: You can use this feature with babel or another compiler enabling the ES2020 features.
Reference
Did you like it? Comment, share! ✨
💖 💪 🙅 🚩
Helder Burato Berto
Posted on June 9, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.