
ES6: useful tips and tricks
- Transfer
The EcmaScript 2015 (ES6) standard has been around for several years. He brought with him many new opportunities, the various ways of using which are far from always obvious. Here is an overview of some of these features with examples and comments.

ES6 allows you to set the default values of formal parameters, which allows you to substitute their standard values when calling a function without specifying the values of these parameters. This allows you to set parameters without which the function will not work.
In the following example, we define the function
The reduce method of an object is
Please note that in the following examples, we rely on the fact that the initial value of the variable is either an array or an object, and not something like a string or number.
Imagine that we have the following task. There is a list of elements, each of which needs to be modified (which reduces to using the map method ), and then select several elements from it (this can be done using the filter method ). This problem is completely solved by the consistent application of the methods
In the following example, you need to double the value of each element in the array, and then select only those that are more than 50. Note how we can use the powerful method
If you have analyzed the above example, then it will be completely obvious to you that you can use the method
Here is another example of the useful features of the method
Suppose we have a line with brackets, and we need to find out if they are balanced, that is, firstly, whether the number of opening brackets is equal to the closing brackets, and secondly, that the corresponding opening brackets are before the closing brackets.
This problem can be solved using the method
Sometimes you need to count the same elements of an array or convert the array to an object. To solve these problems can also be used
In the following example, we want to count the number of cars of each type and put the results of these calculations into an object.
In fact, the possibilities
It so happens that unnecessary properties are required to be removed from an object. Perhaps these are properties that contain classified information, perhaps they are too large. Instead of iterating over the entire object and deleting similar properties, you can extract these properties into variables and leave the desired properties in the rest parameter.
In the following example, we need to get rid of the properties of
In the following example, a property
ES6 supports a spread operator that looks like three dots. Usually it is used to work with arrays, but it can be used with ordinary objects.
In the following example, we use the extension operator to form a new object from two existing ones. The property keys of object # 2 will override the property keys of object # 1. In particular, properties from
In ES6, you can get rid of duplicate values using collections ( Set ). Collections can only contain unique values.
Converting collections to arrays is no more complicated than using the above extension operator. All array methods can also be used with collections.
Suppose we have a collection that needs to be filtered so that it contains only elements that are greater than 3. Here's how to do it.
It often happens that a function returns a set of values as an array. You can extract these values from the array using the destructuring technique.
Here is an example of how new tools for working with arrays allow you to organize the exchange of values of two variables.
In the following example, we download a certain article located at the address
Destructuring makes it easy to assign the results of a function to the appropriate variables.
In this article, we looked at a few simple but unobvious tricks to use the new features of ES6. We hope you find them useful.
Dear readers! If you know any interesting tricks for using ES6 features, please share them.


1. Required function parameters
ES6 allows you to set the default values of formal parameters, which allows you to substitute their standard values when calling a function without specifying the values of these parameters. This allows you to set parameters without which the function will not work.
In the following example, we define the function
required()
as the default value for a
and b
. This means that if you a
or b
will not be passed to the function when you call, the function will be called required()
and we will get an error message.const required = () => {throw new Error('Missing parameter')};
//При вызове этой функции произойдёт ошибка, если параметры "a" или "b" не заданы
const add = (a = required(), b = required()) => a + b;
add(1, 2) //3
add(1) // Error: Missing parameter.
2. Secrets of the reduce method
The reduce method of an object is
Array
extremely versatile. Usually it is used to convert an array of certain elements to a single value. However, with its help you can do a lot more useful. Please note that in the following examples, we rely on the fact that the initial value of the variable is either an array or an object, and not something like a string or number.
▍2.1. Using reduce to perform mapping and filtering an array at the same time
Imagine that we have the following task. There is a list of elements, each of which needs to be modified (which reduces to using the map method ), and then select several elements from it (this can be done using the filter method ). This problem is completely solved by the consistent application of the methods
map
and filter
, but so you have to go through the list of elements twice. But this does not suit us. In the following example, you need to double the value of each element in the array, and then select only those that are more than 50. Note how we can use the powerful method
reduce
to double and filter elements. It is very effective.const numbers = [10, 20, 30, 40];
const doubledOver50 = numbers.reduce((finalList, num) => {
num = num * 2; //удвоить каждое число (аналог map)
//отобрать числа > 50 (аналог filter)
if (num > 50) {
finalList.push(num);
}
return finalList;
}, []);
doubledOver50; // [60, 80]
▍2.2. Using reduce instead of map or filter
If you have analyzed the above example, then it will be completely obvious to you that you can use the method
reduce
instead of map
or filter
.▍2.3. Using reduce to analyze parenthesis
Here is another example of the useful features of the method
reduce
. Suppose we have a line with brackets, and we need to find out if they are balanced, that is, firstly, whether the number of opening brackets is equal to the closing brackets, and secondly, that the corresponding opening brackets are before the closing brackets.
This problem can be solved using the method
reduce
as shown below. Here we use a variable counter
with an initial value of 0. We increase its value by one if we find the symbol "(", and decrease if we find the symbol ")". If the brackets in the line are balanced, the output should be 0.//Возвращает 0 если скобки сбалансированы.
const isParensBalanced = (str) => {
return str.split('').reduce((counter, char) => {
if(counter < 0) { //matched ")" before "("
return counter;
} else if(char === '(') {
return ++counter;
} else if(char === ')') {
return --counter;
} else { //найден какой-то другой символ
return counter;
}
}, 0); //<-- начальное значение для счётчика
}
isParensBalanced('(())') // 0 <-- скобки сбалансированы
isParensBalanced('(asdfds)') //0 <-- скобки сбалансированы
isParensBalanced('(()') // 1 <-- скобки несбалансированы
isParensBalanced(')(') // -1 <-- скобки несбалансированы
▍2.4. Counting the number of matching array values (transforming an array into an object)
Sometimes you need to count the same elements of an array or convert the array to an object. To solve these problems can also be used
reduce
. In the following example, we want to count the number of cars of each type and put the results of these calculations into an object.
var cars = ['BMW','Benz', 'Benz', 'Tesla', 'BMW', 'Toyota'];
var carsObj = cars.reduce(function (obj, name) {
obj[name] = obj[name] ? ++obj[name] : 1;
return obj;
}, {});
carsObj; // => { BMW: 2, Benz: 2, Tesla: 1, Toyota: 1 }
In fact, the possibilities
reduce
are not limited to this. If you are interested in details about this useful method, study the examples from this page.3. Object restructuring
▍3.1. Removing Unnecessary Properties
It so happens that unnecessary properties are required to be removed from an object. Perhaps these are properties that contain classified information, perhaps they are too large. Instead of iterating over the entire object and deleting similar properties, you can extract these properties into variables and leave the desired properties in the rest parameter.
In the following example, we need to get rid of the properties of
_internal
and tooBig
. They can be assigned to variables with the same names and save the remaining properties in the rest parameter cleanObject
, which can be used later.let {_internal, tooBig, ...cleanObject} = {el1: '1', _internal:"secret", tooBig:{}, el2: '2', el3: '3'};
console.log(cleanObject); // {el1: '1', el2: '2', el3: '3'}
▍3.2. Restructuring nested objects in function parameters
In the following example, a property
engine
is a nested object of an object car
. If we need to know, say, a property of an vin
object engine
, it can easily be destructed.var car = {
model: 'bmw 2018',
engine: {
v6: true,
turbo: true,
vin: 12345
}
}
const modelAndVIN = ({model, engine: {vin}}) => {
console.log(`model: ${model} vin: ${vin}`);
}
modelAndVIN(car); // => model: bmw 2018 vin: 12345
▍3.3. Merge Objects
ES6 supports a spread operator that looks like three dots. Usually it is used to work with arrays, but it can be used with ordinary objects.
In the following example, we use the extension operator to form a new object from two existing ones. The property keys of object # 2 will override the property keys of object # 1. In particular, properties from
b
and override the same properties of an object .c
object2
object1
let object1 = { a:1, b:2,c:3 }
let object2 = { b:30, c:40, d:50}
let merged = {…object1, …object2} //применим оператор расширения для формирования нового объекта
console.log(merged) // {a:1, b:30, c:40, d:50}
4. Collections
▍4.1. Removing duplicate values from arrays
In ES6, you can get rid of duplicate values using collections ( Set ). Collections can only contain unique values.
let arr = [1, 1, 2, 2, 3, 3];
let deduped = [...new Set(arr)] // [1, 2, 3]
▍4.2. Using Array Methods with Collections
Converting collections to arrays is no more complicated than using the above extension operator. All array methods can also be used with collections.
Suppose we have a collection that needs to be filtered so that it contains only elements that are greater than 3. Here's how to do it.
let mySet = new Set([1,2, 3, 4, 5]);
var filtered = [...mySet].filter((x) => x > 3) // [4, 5]
5. Array destructuring
It often happens that a function returns a set of values as an array. You can extract these values from the array using the destructuring technique.
▍5.1. Exchange of variable values
Here is an example of how new tools for working with arrays allow you to organize the exchange of values of two variables.
let param1 = 1;
let param2 = 2;
//поменяем местами значения param1 и param2
[param1, param2] = [param2, param1];
console.log(param1) // 2
console.log(param2) // 1
▍5.2. Receiving and processing multiple values returned by a function
In the following example, we download a certain article located at the address
/post
, and related comments from the address /comments
. Here the construction is applied async/await
, the function returns the result in the form of an array. Destructuring makes it easy to assign the results of a function to the appropriate variables.
async function getFullPost(){
return await Promise.all([
fetch('/post'),
fetch('/comments')
]);
}
const [post, comments] = getFullPost();
Summary
In this article, we looked at a few simple but unobvious tricks to use the new features of ES6. We hope you find them useful.
Dear readers! If you know any interesting tricks for using ES6 features, please share them.
