JavaScriptArrays
Array. prototype. push()
Adds elements to the end of an array and returns its new length.
- Returns
- The new length of the array.
- Changes the original
- Yes
Example
#JavaScript
const cart = ['HTML Course']
const newLength = cart.push('CSS Course', 'JS Course')
console.log(newLength)
console.log(cart)Console
3
['HTML Course', 'CSS Course', 'JS Course']
Definition and usage
#The push() method appends one or more elements to the end of the array. It changes the original array and returns its new length, not the array itself.
It’s the most common way to add data: a new chat message, a task on a list, a result in the history.
In code built around data immutability (like React state), you create a new array instead of using push(): [...items, newItem].
Syntax
#Syntax
array.push(element1, element2, …)Parameters
#element1…elementN
any values
The elements to add at the end.
More examples
#JavaScript
const cart = ['HTML Course']
const updated = [...cart, 'Python Course']
console.log(cart)
console.log(updated)Console
['HTML Course']
['HTML Course', 'Python Course']
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Don’t assign the result of
push()back to the array:list = list.push(x)turns the array into a number. - To merge two arrays, use
concat()or the...syntax, notpush()with an array (it would add the whole thing as a single element).
Related entries
#- Array.prototype.pop()Removes the last element of an array and returns it.
- Array.prototype.unshift()Adds elements to the start of an array and returns its new length.
- Array.prototype.concat()Combines arrays and values into a new array.
- Spread (...)The spread syntax spreads an array, string, or object out into individual elements: for copying, merging, and passing arguments.
Spotted a mistake or missing an example? Write to us.