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>
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>
Happy coding. 🙂
Articles you don't want to miss 👇