12 Helpful Javascript Features from ES6 to ES2021

Dhimas Yoga
DSF Web Services Engineering
10 min readMar 2, 2023

There are many browsers out there that came with different script languages. One of them is JScript by Microsoft. As web developers, we need to make sure that the script we developed will be able to run in those browsers. EcmaScript (commonly abbreviated as ES) was created to make a language standard for many different script languages out there, so web pages written in ES can run properly in various types of existing browsers.

ES is a code writing or language specification standard in Ecma-262 created by Ecma International. Ecma International is an organization to develop standards for information and communication systems and technology, while Ecma-262 is built specifically for script languages. ES is kept updated (almost) every year. The first EcmaScript version, ES1, was released in 1997 and kept evolving into ES6 in 2015. After ES6, the ES version naming was changed based on the year it was released. Don’t get puzzled if you read ‘ES6 or ES2015’ somewhere on the internet because it refers to the same version of ES. Today, the latest version is ES2021.

Each version of ES brings new code features and also enhancement of previously existing features. It can help the developer to write code easier and efficiently. In this article, I will try to summarize some helpful features that we can derive from ES6 to ES2021. All those features will enable you to work more effectively. Keep your thumb scrolling the screen down to know more about them!

A. EcmaScript 6

ES6 is by far the greatest improvement to JS since 1996. It was introduced in 2015. There are many features in this version, such as destructuring, spread operator, rest parameter, default parameter, template literals, arrow functions, and for…of loop.

1. The … Operator

We can use the operator in two ways:

a. Spread Operator

The spread operator can be used to copy an array or object whether by combining it or destructuring it. The example below shows how to combine two arrays using the spread operator.

const groupOne = ['Niragi', 'Chisiya', 'Arisu']
const groupTwo = ['Ann', 'Usagi', 'Kuina']

const combineGroup = [...groupOne, ...groupTwo]

In the example above, we can see an array containing some values like ‘Niragi’, ‘Chisiya’, and ‘Arisu’ and another one containing the value ‘Ann’, ‘Usagi’, and ‘Kuina’. We will combine the values in both arrays into one by using the spread operator. The output will be like this:

Niragi, Chisiya, Arisu, Ann, Usagi, Kuina

In the process of copying the array or object using the spread operator, there are two processes that happened in the background based on the following conditions:

1. Deep copy the whole object/array for those which does not have nested item.

2. If the object/array have nested item(s), it deep copies the outermost item first, then shallow copy the nested item(s).

We can also use the spread operator to do an array destructuring. In the example below, we have an array of numbers. We want to copy it and destructure the data ‘1’ and ‘2’… but let the rest of them be. We can use the spread number and the output will be like this:

const numbers = [1, 2, 3, 4, 5, 6]
const [one, two, ...rest] = numbers

// output:
// one : 1
// two : 2
// rest : 3,4,5,6

b. Function Rest Parameter

Sometimes, creating different functions and then defining each parameter manually by typing them one by one feels so boring. Do you ever wonder if you can work more effectively by using the function rest parameter, which is a feature in ES6 and above to create a function with a dynamic amount of parameters? Rest parameter syntax allows a function to accept an indefinite number of arguments as an array and provides it a way to represent a variadic function in JS. It means that you do not need to rewrite your code manually over and over again.

Here is an example of how effective using the rest parameter is. Before ES6, you need to write multiple functions to do the same task like below:

function firstFunc(param) {
// do some task...
}
function secondFunc(param1, param2) {
// do some task...
}
function thirdFunc(param1, param2, param3) {
// do some task...
}

It is wasting time, especially when you have a huge amount or an indefinite number of parameters, isn’t it? By using ES6, you can use the… operator to simplify your work by compiling an enormous amount of parameters in a function. Just write the parameter like this:

function myDynamicFunction(...params) {
console.log(params.length)
}

myDynamicFunction(100, 23, 97, 'Clinton', 0.5, 'Thomas')
// output: 6

2. The for-of loop

The For-of loop allows us to iterate over an iterable data structure such as Arrays, Strings, Maps, NodeLists, etc.

Assume we have this iterable data structure (in a form of an array):

const names = ['Alexander', 'Trent', 'Arnold']

Let’s take an example, we want to convert that array into a string. Without using For-of Loop, we will write the code using regular For Loop like this:

let fullName = ''
for(let i = 0; i < names.length; i++) {
fullName += names[i] + ' '
}

console.log(fullName)
// output : Alexander Trent Arnold

By using For-of Loop, it will be more simple and readable:

let fullName = ''
for(let name of names) {
fullName += name + ' '
}

console.log(fullName)
// output : Alexander Trent Arnold

3. includes() Method

The includes() method is a new method in ES6 to find if a string contains or includes a certain value. If the value is found, the output will be true, while if it is not found, the output is false.

const sentence = "Some of popular Javascript frameworks are React, Vue, Angular, and Svelte"
console.log(sentence.includes('React'))

// output: true

Not only for strings, includes() method can also be used in an array like this:

const frameworks = ['React', 'Vue', 'Svelte', 'Angular']
console.log(frameworks.includes('React'))

// output: true

Note:

The includes() method is case sensitive. So if we write ‘react’ instead of ‘React’ in the code, the output will be false.

4. Array find() Method

Array find() method is another new method in ES6. We can use it to find the first item in the array that match a certain condition. This method only accepts a function as a parameter. In the example below, we want to find some items in the array that have values larger than 30. There were two values were found, they are 37 and 98. But we only take the first item.

const numbers = [10, 25, 37, 4, 98]
let first = numbers.find((value, index) => {
return value > 30
})

console.log(first);
// output : 37

5. Array findIndex() Method

Different from find() method, the findIndex() method will only return the index number of the item in the array, not the value. Look at the example code below. We have a parameter for a value less than <10. Only one value is found, it is ‘4’. The output will show the index number.

const numbers = [10, 25, 37, 4, 98]
let getIndex = numbers.findIndex((value, index) => {
return value < 10
})

console.log(getIndex);
// output : 3

Remember that programming languages count everything starting from 0, so it returns 3 in the example above.

B. EcmaScript 2017

6. Object.entries()

The Object.entries() feature will simply make a copy of an iterable object (non-nested object) and change it into a two-dimensional JS array. Each sub-array of the two-dimensional JS array contains a key and a value pair of the object. This is an example of an iterable object we want to change into a two-dimensional JS array. In this case, we want to copy the key “name” dan the value pair “Lionel Messi” into a new array using Object.entries() method.

const player = {
name: 'Lionel Messi',
nationality: 'Argentina',
club: 'Paris Saint Germain',
backNumber: 30
}

let playerArr = Object.entries(player)

The output will be like this:

[
[
"name",
"Lionel Messi"
],
[
"nationality",
"Argentina"
],
[
"club",
"Paris Saint Germain"
],
[
"backNumber",
30
]
]

C. EcmaScript 2019

7. Object.fromEntries()

If the Object.entries() converts an Object into a two-dimensional array, the Object.fromEntries() does the otherwise. It converts a two-dimensional array into an object. Look at the code below. This is an example of a two-dimensional array that we want to convert into an object by putting Object.fromEntries().

const cars = [
["ferrari", 5600],
["audi", 7200],
["bugatti", 9800]
]

let carsObj = Object.fromEntries(cars)

The output of the carsObj will be:

{ferrari: 5600, audi: 7200, bugatti: 9800}

Easy peasy, right? From now on, we do not have to create a function manually only to convert an array into an object.

Pro tip: You can use this feature to print what a formData contains.

8. Array flat()

I can say that the flat() method will convert a two-dimensional array into a one-dimensional array. The process is like ‘flattening’ the array. That is why it is named the flat() method. Basically, it can be used to merge some groups of data into a bigger one. In the example below, we have three groups of data. We use the flat() method to merge the data within the arrays.

const myArr = [[1,2],[3,4],[5,6]];
const newArr = myArr.flat();
// output : [1, 2, 3, 4, 5, 6]

D. EcmaScript 2020

9. Nullish Coalescing Operator (??)

Have you ever tried (or at least hear) about Javascript Ternary Operator? If you haven’t, then read the article here before continuing reading.

By reading the article, now you already know that using the ternary operator has already saved your time and reduced some lines of code. But, what if we meet this condition?

let someVar = obj['a_long_object_key_name'] ? obj['a_long_object_key_name'] : 'Default Value' 

Even though we already use the ternary operator, the code writing here is less efficient and less readable. We can use the ?? operator to make it simpler. Theoretically, it’s like a ternary operator but it will directly return the first argument itself if it is not nullish (a condition when a variable has undefined or null value). I’ll provide you with an example to see how you are going to use it.

let someVar = obj['a_long_object_key_name'] ?? 'Default Value' 

Here by using the nullish coalescing operator, we avoid writing the same “long” object key twice. Technically, it will do the same as the example before but in a more readable way. It’s cool, isn’t it?

10. Optional Chaining Operator (?.)

Sometimes we meet a problem when a dynamic variable returns nullish. As a result, the variable is detected as an error and the program stops running. The optional chaining operator (?.) returns the error as undefined. In the example below, we’re going to get an input column, but assume that the input element doesn’t exist.

// assume the input element doesn't exist, so it will be undefined
const inputNotes = $('#imaginary_input');
const inputLength = inputNotes.val().length

Here we use method chaining to derive the value from ‘inputNotes’ variable first. After that, we count the length of the input value. But, in the process of deriving the data, we cannot find the input or the input doesn’t existed. As a result, an error occurred because we can’t get the value of a non-existing input element and the code execution is stopped. Here, we can use the ?. operator after the name of the variable (or object key) to check whether it’s nullish or not.

By using the optional chaining operator, it won’t continue the method chaining when the variable is nullish. Instead of throwing an error, it will directly assign it into ‘undefined’ to the inputLength variable and the code execution will continue running (not stopped). Look at the image below for a clearer view:

E. EcmaScript 2021

11. String replaceAll()

Previously, Javascript already had a replace() function. Unfortunately, it cannot be used for multiple same values. It only replaces the first matched value, so we need to use it repeatedly to replace multiple same words (one by one).

Look at the example below:

The replace() function only replace the first word that matches the value we typed into the parameter

The good news is that ES2021 gives you a solution by adding replaceAll() feature. By using this function, we can replace every matching value at once.

replaceAll() function will actually replace all the matching value within the string

Replacing things is now quicker and easier, isn’t it?

12. Numeric Separators

The last feature that we discuss in this article is Numeric Separators. This feature will give an advantage for humans to read long and big numbers within your code. Previously, we had to write long numbers without separation like this:

const reallyBigNumber = 10000000000

Without any commas or periods, the developers will find it a bit hard to read the value. In ES2021, there is a feature where we can use an underscore (_) sign to separate the number. We can place it within so it will be more readable for humans.

Example:

const reallyBigNumber = 10_000_000_000

Javascript treats this underscore as a regular number when you use it or print it out.

Conclusion

Every upgrade of the EcmaScript version always brings new cool and helpful features to make developers work with the code and process the data easier and more efficiently. It is important to remember that we must keep refreshing our knowledge and information to what’s happening out there. Keep learning, keep practicing, and be a better developer each day.

--

--