EN
JavaScript - spread operator (...)
0
points
In this article, we would like to show you how works spread operator in JavaScript.
Spread operator allows you to spread the iterated value into its components.
Usage examples:
1. Breaking an array into individual elements:
// ONLINE-RUNNER:browser;
const array = [1, 2, 3, 4, 5];
console.log(...array); // 1, 2, 3, 4, 5
// split the text into individual letters
const string = "Dirask";
console.log(...string); // D, i, r, a, s, k
2. Copying an array:
// ONLINE-RUNNER:browser;
const array = [1, 2, 3, 4, 5];
const array2 = [...array];
console.log(array2); // 1, 2, 3, 4, 5
3. Combine arrays:
// ONLINE-RUNNER:browser;
const array1 = [2, 3, 4]
const array2 = [1, ...array1, 5, 6, 7];
console.log(array2); // 1, 2, 3, 4, 5, 6, 7
4. Math
object.
Functions like Math.max()
expect many parameters. We can't pass the array as one argument there, so we can use the spread
operator.
// ONLINE-RUNNER:browser;
let array = [1, 2, 3, 4];
console.log(Math.max(1, 2, 3, 4)); // 4
console.log(Math.max(array)); // NaN
console.log(Math.max(...array)); // 4
5. We can also apply the spread operator to objects.
// ONLINE-RUNNER:browser;
const object1 = {
x : 5,
y : 7
}
const object2 = {
y : 11,
z : 23
}
const object3 = {
k: 33,
...object1,
...object2
};
object3String = JSON.stringify(object3, null, 4);
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.