The spread operator can turn the elements of an array into elements of a function call or into elements of another array literal.
For example, let’s create an array of cars
let cars = ['tesla', 'toyota', 'honda'];
as well as another array of bikes:
let bikes = ['bajaj', 'kawasaki', 'jincheng'];
However, if we were to create another array which we would like to have the elements in our
bikes contained as well, eg:
let vehicles = ['Truck', 'Jeep', 'Boat', cars, bikes, 'Jet''];
When we log
vehicles to the console with
console.log(vehicles) we should get a result similar to this:
Instead of making it appear as an array of arrays such as we have here, we can make the elements of cars and bikes appear as natural elements of the parent
vehicles array by making use of the spread operator.
let vehicles = ['Truck', 'Jeep', 'Boat', ...cars, ...bikes, 'Jet''];
If we console.log the
vehicles variable, we see that variables
bikes appear as normal elements and not as a sub-array anymore.
So far, I hope we get a glimpse of how handy spread operators can be, especially when working with large data sets.
What do you think of the Spread operator?