JavaScript Glossary: Array .push() Method
Publikováno: 8.2.2019
Basics
This methods appends one or more value to the last position of an array. This method mutates the array returning the new length of the array.
let ...
Basics
This methods appends one or more value to the last position of an array. This method mutates the array returning the new length of the array.
let newArray = [1, 2, 3, 4, 5].push(6)
// [1, 2, 3, 4, 5, 6]
https://scotch.io/embed/gist/f856cd93aad2951ec4d8cbb83780862a
The push
method:
- Takes a value or values as arguments.
- Adds the value(s) to the end of the array.
- Returns the new length of the array.
Syntax
array.push(element)
1 Parameter
element This is the element to be added to the array
Returns the length of the array
The method will return the new length of the array. If the array is empty, it returns 0
.
const names = ['Johnny', 'Pete', 'Sammy']
console.log(names.push('Larry'));
// output: 4
The .push() method mutates the old array.
Common Uses and Snippets
Appending new values to the end of an array
https://scotch.io/embed/gist/e606571a20b9ff2f5ab32fb76b59b5fc
Adding object values to an array of objects
This is used in situations like adding todo items to a todo list.
https://scotch.io/embed/gist/1721d1efc46721131d750076ae1a2133