cft

4 JavaScript 2021 Pro Tips for Writing Cleaner Code

Take your JavaScript to the next level in 4 simple moves.


user

Piero Borrelli

2 years ago | 1 min read

JavaScript is a fantastic language, but it can become even better if you use of its latest features getting released every year. In 2021, ES12 is king, so let’s see how its best features can immediately improve your code starting by today.

1. Use replaceAll

Earlier, when using JavaScript, there was no way to replace all instances of a substring in a string without the use of the global regexp (/regexp/g). But now, things have changed thanks to the replaceAll method.

2. Use Logical Assignment Operators

These newly introduced operators combine the power of assignment and logic operations.

The logical x||=y works like this: if x is truthy, it returns x. Otherwise, it assigns yto x.

While x&&=only assigns yif xis truthy

3. Use Numeric separators

This is a feature I love so much. And it’s so trivial that I wonder why it hasn’t been part of the language since its first days. With numeric separators, you can separate thousands in your numbers, making them a lot more readable:

4. Use Promise.any()

The Promise.any() method resolves as soon as any of the promises you passed to it becomes resolved. Contrarly to Promise.race() , it doesn’t reject early when one of the promises rejects.

One example where this method could be useful? Retrieving resources from the fastest server.

Conclusion

JavaScript is amazing, but it can become even better if you know how. Hopefully, I’ve helped you to do that with this piece.

— Piero

Upvote


user
Created by

Piero Borrelli


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles