Home

SiteMap

A Practical use of JavaScript Spread Operator

← PrevNext →

Let us assume, I have an array with few items in it.
let arrBirds = ['Bald Eagle', 'Black Vulture']; Now at run-time, I want to "quickly" add some more items (bird names) in the array. The quickest and the easiest method (to do this) that comes to my mind is the spread operator (...).
<script>
  let arrBirds = ['Bald Eagle', 'Black Vulture'];
  arrBirds = [...arrBirds, 'Snail Kite', 'Gila Woodpecker', 'White-tailed Hawk'];

  document.write('Result: ' + arrBirds);

  // Output: Bald Eagle,Black Vulture,Snail Kite,Gila Woodpecker,White-tailed Hawk
</script>
Try it

See the "second" line in the above script, where I am using the spread operator, three "dots" followed by the array. With it I am adding three more items (bird names) to the array.

Its better than the .push() method, which is also used to add items to an array.

Convert String to Array using spread (...) Operator

You can use the spread operator to convert a string into an array. See this example.

<script>
  let name = 'arun'
  
  let arr = [...name];
  document.write(arr);

  // Output: a,r,u,n
</script>
Try it

Happy coding. 🙂

Articles you don't want to miss 👇
What is map() function in JavaScript? Benefits of using map() function in your application.
How to get the X character (any particular character) in a string using JavaScript
What is Ternary operator in JavaScript and how to use it?

← PreviousNext →