Skip to content
Advertisement

How to append something to an array?

How do I append an object (such as a string or number) to an array in JavaScript?

Advertisement

Answer

Use the Array.prototype.push method to append values to the end of an array:

JavaScript

You can use the push() function to append more than one value to an array in a single call:

JavaScript

Update

If you want to add the items of one array to another array, you can use firstArray.concat(secondArray):

JavaScript

Update

Just an addition to this answer if you want to prepend any value to the start of an array (i.e. first index) then you can use Array.prototype.unshift for this purpose.

JavaScript

It also supports appending multiple values at once just like push.


Update

Another way with ES6 syntax is to return a new array with the spread syntax. This leaves the original array unchanged, but returns a new array with new items appended, compliant with the spirit of functional programming.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement