5 New JavaScript Features To Check Out (ECMAScript 2021)

5 New JavaScript Features To Check Out (ECMAScript 2021)

1. replaceAll()

A very quick way to replace strings without the need of regular expressions.

const p = 'Bob likes to take a walk every morning. Bob has a healthy habbit'

console.log(p.replaceAll('Bob', 'Alice'))
// Output: Alice likes to take a walk every morning. Alice has a healthy habbit

2. Logical Assignment Operators

You can save some lines of code with the new logical assignment operators.

Let's say you have something like this:

// Old way
let x = 1
let y = 2

if(x) {
  x = y
}

Now you can do it like this:

// New way
let x = 1
let y = 2

x &&= y
  • && = if(x)
  • || = if(!x)

3. Numeric Separators

You can make numeric literals more readable by simply adding underscores.

// Lets say you have something like this
let x = 1000000

// You can also write it likes this
let x = 1_000_000

4. Nullish Coalescing

// Old way
if (taxes == null) {
  taxes = 0.05
}

// New way
taxes = taxes ?? 0.05

It basically means: If a value is null or undefined then fallback to the default value.

5. Style Your Console Log

If you're sometimes using console logs to debug parts of your code, adding style to your console logs can help with readability.

You can achieve this by adding %c before the text you want to style and then inserting one more argument to the console log function with the style you want to apply.

For example, we want to console log the price of an item, and we want the price to have a green color so it stands out.

let price = 100

console.log(`Item price: %c${price}`, 'color: green')

console log output