DEV Community

Discussion on: 17 Javascript optimization tips to know in 2021 🚀

Collapse
 
denisdiachenko profile image
DenisDiachenko

That's a good list, just one thing I would like to mention in tips 4 and 5. It's better to check if the value is null or undefined using Nullish Coalescing Operator (??) since for some cases it might be an unexpected behavior:

const foo = null || 42;
console.log(foo);
// expected output: 42
Enter fullscreen mode Exit fullscreen mode
const foo = 0 || 42;
console.log(foo);
// expected output: 0, but will be 42
Enter fullscreen mode Exit fullscreen mode

So, in that case ?? will work as expected

const baz = 0 ?? 42;
console.log(baz);
// expected output: 0 and will be 0
Enter fullscreen mode Exit fullscreen mode

Thank you for your work!

Collapse
 
blessinghirwa profile image
Blessing Hirwa

In some cases Nullish Coalescing Operator is the best choice. Thanks for the assistance.