JavaScript spread operator
A spread operator looks like this.
[…array];
three dots followed by an array.
The spread operator can be used in many ways, like combining arrays, adding new items to an array at run time, adding a new property to an object etc.
Let us see how we can add new item(s) to an array using the spread operator.
<script> const arr_members = ['arun', 'shouvik']; const arr_family = ['banik', ...arr_members]; console.log(arr_family); // Output: (3) ['banik', 'arun', 'shouvik'] </script>
The array arr_members has two string values. I have added a new item (a string value) banik and created a new array (arr_family) using the (…) spread operator. The "const" keyword will not allow me to add new items to the first array.
However, you can add new items to the existing array. For example,
<script> let arr_members = ['arun', 'shouvik']; arr_members = ['banik', ...arr_members]; console.log(arr_members); // Output: (3) ['banik', 'arun', 'shouvik'] </script>
The array is not a const. Therefore, now I can alter the array by adding a new item to the array.
Similarly, you can pass multiple values (items).
<script> let arrBirds = ['Mourning Dove', 'Rock Pigeon']; arrBirds = [...arrBirds, 'Black Vulture', 'Snail Kite']; console.log(arrBirds); // Output: (4) ['Mourning Dove', 'Rock Pigeon', 'Black Vulture', 'Snail Kite'] </script>
🚀 JavaScript operators every beginner should know
Adding spread operator Multiple times
You can add the "spread" operator multiple times to add items to an array. For example,
<script> const arrDove = ['Mourning Dove', 'Rock Pigeon']; const arrHawk = ['Black Vulture', 'Snail Kite']; let arrBirds = [...arrDove, ' are Doves and ', ...arrHawk, ' are Hawks']; console.log(arrBirds); // Output: (6) ['Mourning Dove', 'Rock Pigeon', ' are Doves and ', 'Black Vulture', 'Snail Kite', ' are Hawks'] </script>
The first two array items are added to a third array using the (…) spread operator twice, along with string values.