Home >Web Front-end >JS Tutorial >How Can I Append Elements to an Array in JavaScript?

How Can I Append Elements to an Array in JavaScript?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-14 03:35:13917browse

How Can I Append Elements to an Array in JavaScript?

Appending Elements to Arrays in JavaScript

In JavaScript, arrays are used to store collections of elements. When you need to add new elements to an existing array, there are two common methods:

Array.prototype.push

The most common method to append an element to an array is to use the Array.prototype.push method. This method adds one or more new elements to the end of an array and returns the new length of the array.

// initialize array
var arr = [
  "Hi",
  "Hello",
  "Bonjour"
];

// append new value to the array
arr.push("Hola");

console.log(arr); // [ 'Hi', 'Hello', 'Bonjour', 'Hola' ]

Spread Operator

Another way to append an element to an array is to use the spread operator (...). This operator allows you to spread the elements of an existing array into a new array, and then add new elements to the end.

// initialize array
var arr = [
  "Hi",
  "Hello",
  "Bonjour"
];

// append new value to the array using the spread operator
var newArr = [...arr, "Hola"];

console.log(newArr); // [ 'Hi', 'Hello', 'Bonjour', 'Hola' ]

Both methods achieve the same result, but the Array.prototype.push method is more convenient when you only need to append a few elements to an array. For more complex manipulations, the spread operator offers greater flexibility.

The above is the detailed content of How Can I Append Elements to an Array in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn