W3jar
316 words
2 minutes

How to Append an Item to an Array in JavaScript

Appending an item to an array in JavaScript is a common operation and can be done in a few different ways:

Method 1: Using push() method#

The push() method adds one or more elements to the end of an array and returns the new length of the array.

let array = [1, 2, 3, 4];
array.push(5);

console.log(array); // Output: [1, 2, 3, 4, 5]

Method 2: Using the spread operator (...)#

You can use the spread operator (...) to append an item at the end of an array. This method creates a new array and is useful when you want to avoid mutating the original array.

let array = [1, 2, 3, 4];
let newItem = 5;

let newArray = [...array, newItem];

console.log(newArray); // Output: [1, 2, 3, 4, 5]

Method 3: Using the concat() method#

The concat() method is used to merge two or more arrays. It doesn’t mutate the original arrays, instead it returns a new array. You can pass the item you want to append as an argument to concat().

let array = [1, 2, 3, 4];
let newItem = 5;

let newArray = array.concat(newItem);

console.log(newArray); // Output: [1, 2, 3, 4, 5]

While less common, you can directly assign a value to a specific index of the array to append an item. This approach modifies the original array and is generally less preferred unless you specifically need to replace an existing item.

let array = [1, 2, 3, 4];
array[array.length] = 5;

console.log(array); // Output: [1, 2, 3, 4, 5]

Summary#

  • push(): Mutates the original array by adding elements to the end.
  • Spread Operator (...): Creates a new array by combining existing array with new elements.
  • concat(): Creates a new array by concatenating arrays or adding elements.
  • Direct Index Assignment: Modifies the original array by assigning a value directly.

The choice of method depends on whether you want to mutate the original array or create a new array, and your specific use case.