Image de l'article 'Simplify your ifs in JavaScript and TypeScript'

Simplify your ifs in JavaScript and TypeScript

Code quality, is that something you take care of in your everyday tasks? I do. But sometimes, it is not simply just about saving keystrokes or a number of characters. Let’s dive into it

Let’s suppose you have the following:

const result = value1;
if (result === null || result === undefined) {
  result = value2;

How can you reduce it to one line without writing if ?

const result = value1 ?? value2;

OK, you gain 3 lines, but before you use it everywhere, think about 2 things for your use cases:

  1. Is it changing something to the performance of your application?
  2. Is it going to be as readable as the 3 lines to anyone, senior and junior?

Maybe, in the example, it’s OK to use the Nullish coalescing operator.

I would say it isn’t always the case.

Please read the MDN article on the Nullish coalescing operator on the topic.

Also check out this article which I liked because it goes in detail with nice use cases.

Thanks for reading.

License GPLv3 | Terms
Built with Hugo
Theme Stack designed by Jimmy