How to add new items to an Array in JavaScript (…) spread operator

← PrevNext →

Let us assume, you are using array in JavaScript and the array has few items. Later during a process, you’ll have to add more items to the array dynamically (at run time). One common method that web developers use is the .push() method. In-addition, you can use the spread (…) operator to add new items to an array.

JavaScript spread operator

A spread operator looks like this.


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.

  const arr_members = ['arun', 'shouvik'];
  const arr_family = ['banik', ...arr_members];

  // Output: (3) ['banik', 'arun', 'shouvik']
Try it

JavaScript spread operator example

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,

  let arr_members = ['arun', 'shouvik'];
  arr_members = ['banik', ...arr_members];

  // Output: (3) ['banik', 'arun', 'shouvik']

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).

  let arrBirds = ['Mourning Dove', 'Rock Pigeon'];
  arrBirds = [...arrBirds, 'Black Vulture', 'Snail Kite'];

  // Output: (4) ['Mourning Dove', 'Rock Pigeon', 'Black Vulture', 'Snail Kite']
Try it

🚀 JavaScript Operators that you should know.

Adding spread operator Multiple times

You can add the "spread" operator multiple times to add items to an array. For example,

  const arrDove = ['Mourning Dove', 'Rock Pigeon'];
  const arrHawk = ['Black Vulture', 'Snail Kite'];
  let arrBirds = [...arrDove, ' are Doves and ', ...arrHawk, ' are Hawks'];

  // Output: (6) ['Mourning Dove', 'Rock Pigeon', ' are Doves and ', 'Black Vulture', 'Snail Kite', ' are Hawks']
Try it

Adding multiple spread operators to an array in JavaScript

The first two array items are added to a third array using the (…) spread operator twice, along with string values.

Happy coding.

← PreviousNext →