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.

[…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>
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,

<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>
Try it

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

← PreviousNext →