EN
JavaScript - spread operator (...)
0 points
In this article, we would like to show you how works spread operator in JavaScript.
The spread operator allows you to spread the iterated value into its components.
Usage examples:
xxxxxxxxxx
1
const array = [1, 2, 3, 4, 5];
2
console.log(array); // 1, 2, 3, 4, 5
3
4
// split the text into individual letters
5
const string = "Dirask";
6
console.log(string); // D, i, r, a, s, k
xxxxxxxxxx
1
const array = [1, 2, 3, 4, 5];
2
const array2 = [array];
3
console.log(array2); // 1, 2, 3, 4, 5
xxxxxxxxxx
1
const array1 = [2, 3, 4]
2
const array2 = [1, array1, 5, 6, 7];
3
console.log(array2); // 1, 2, 3, 4, 5, 6, 7
Functions like Math.max()
expect many parameters. We can't pass the array as one argument there, so we can use the spread
operator.
xxxxxxxxxx
1
let array = [1, 2, 3, 4];
2
3
console.log(Math.max(1, 2, 3, 4)); // 4
4
console.log(Math.max(array)); // NaN
5
console.log(Math.max(array)); // 4
6
xxxxxxxxxx
1
const object1 = {
2
x : 5,
3
y : 7
4
}
5
6
const object2 = {
7
y : 11,
8
z : 23
9
}
10
11
const object3 = {
12
k: 33,
13
object1,
14
object2
15
};
16
17
const object3String = JSON.stringify(object3, null, 4);
18
console.log(object3String); // { k : 33, x : 5, y : 11, z : 23 }
As we can see above, the order does matter - y
value from Object1
has been overridden by value from Object2
.
Note:
There is also the
rest
operator (...
) which looks the same and works quite similar, but there are a few differences between thespread
operator and therest
operator, which you can read about here.