Best Way to Append to Array in JavaScript

How can I javascript append to array? What is the best way to append an object, like a string or number, to an array in JavaScript?

In my experience, the most common way to handle a JavaScript append to array is using the push() method. This method adds one or more elements to the end of an array in a straightforward manner. Here’s a simple example:

var myArray = [1, 2, 3];  
myArray.push(4); // Appends a number  
myArray.push('hello'); // Appends a string  

console.log(myArray); // Output: [1, 2, 3, 4, 'hello']  

The push() method is clean, concise, and quite commonly used.

Another approach you might find useful for JavaScript append to array is using the concat () method. This method doesn’t modify the original array; instead, it creates a new array containing the original elements along with the new ones you want to add. Here’s how it works:

var myArray = [1, 2, 3];  
var newArray = myArray.concat(4, 'hello'); // Appends a number and a string  

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

This can be handy when you want to avoid mutating the original array.

In addition to push() and concat (), you can also use the spread operator (...) for a JavaScript append to array operation. This method is not only concise but also powerful when you need to merge or expand arrays dynamically:

var myArray = [1, 2, 3];  
myArray = [...myArray, 4, 'hello']; // Appends a number and a string  

console.log(myArray); // Output: [1, 2, 3, 4, 'hello']  

The spread operator is great when you want a clean syntax for merging or appending multiple elements or even entire arrays.