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! ✨
Top comments (0)