In this short post, I will be explaining one way to use the ...
notation.
If you want to spread out an array into another array, you can use three dots (...
).
This is a bit easier to understand with an example.
JavaScript Code
let arr1 = ["a1", "a2", "a3"];
let arr2 = ["b1", arr1, "b2", "b3"];
let arr3 = ["b1", ...arr1, "b2", "b3"]
In the above code, arr2 and arr3 are not the same things.
When we try to use console.log on our arr2, we will get:
However, when we use console.log on arr3, the result we see is:
You will notice that in arr2
, we have 4 elements, and one of the element itself is an array. This is the arr1
that we added.
However, in arr3
, we have 6 elements because all the elements of arr1
are spread out. This happened because we use the three dot (...
) notation: it spreads out the elements in arr1
.