Thursday 30 September 2021

Some new features from ES2021 I really like

Go, JavaScript! ES2021 was made public around last June, and with it, some pretty neat new features. I'm not going through all of them today, but some of them do merit a mention here because I have thoughts on them.

The replaceAll() method

It used to be the replace() method on strings would replace the first occurrence of a string within another string, and only that. If you wanted to replace all occurrences, you had to use a Regular Expression. (Here's a link if you're interested.)

Well, no longer! Now the replaceAll() method does this easily.

let str = "David is the most awesome man alive. David rides a Harley-Davidson. David has a fantastic sense of style.";
let str2 = str.replaceAll("David", "John");

console.log(str2); // John is the most awesome man alive. John rides a Harley-Johnson. John has a fantastic sense of style.


So I'm left with one question: why the fuck did it take so long to implement something as easy as this?! Between the time JavaScript first came out and now, that's easily fifteen years!

Underscore in numerical values

This sweet new feature allows the programmer to place underscores within a numerical value.

let num = 9129302500;
let num2 = 9_129_302_500; // this is equal to num


If the utility of this is not immediately obvious, think of what happens when you have to deal with extremely large numbers. If you're dealing with five digits or less, granted, it's not of much use. But if you're dealing with more than that, the underscore gives you an easy visual separator.

This is great! Simple and innovative.

Logical assignment operator

There's actually a lot more to this particular update, but I'm only going to cover this part.

The "??" operator now functions as shorthand for a conditional block. It checks the preceding expression for a null or undefined value, and executes the following expression if so.
let x = null;
let y = 9999;
let z = 10000;

x ??= y + z;
y ??= z;

console.log(x); // 19999
console.log(y); // 9999


Wow, this is so lazy. I approve!

Awesome!

The updates weren't as complicated as I initially feared. About half of them I actually understand and could conceivably use. These potentially make code more hassle-free and readable.

("Havexaxnicexday!").replaceAll("x", " ");
T___T

No comments:

Post a Comment