How do I append an object (such as a string or number) to an array in JavaScript?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use the
Array.prototype.pushmethod to append values to the end of an array:You can use the
push()function to append more than one value to an array in a single call:Note that the
push()method returns the updated length of the array.Update
If you want to add the items of one array to another array, you can use
firstArray.concat(secondArray):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.unshiftfor this purpose.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 or prepended, compliant with the spirit of functional programming.