Add Element to Array in JavaScript
In JavaScript, Array.push() method is used to append or add an element to the end of array.
Syntax
array.push(element1, element2, .., elementN)
array
is an array of elements.push
is the array method name.element1
,element2
, ..,elementN
are the elements that must be added to the end of the array.
push()
method adds the given elements (as arguments) to the array
. push()
method modifies the original array, and returns the length of the new resulting array.
Examples
- Add an element to the end of the array
numbers
.
let numbers = [5, 1, 7, 3];
let newLength = numbers.push(8);
console.log('New length of array : ' + newLength);
console.log(numbers);
2. Add 3 elements to the array numbers
.
let numbers = [5, 1, 7, 3];
let newLength = numbers.push(8, 74, 100);
console.log('New length of array : ' + newLength);
console.log(numbers);
3. No argument to push() method.
let numbers = [5, 1, 7, 3];
let newLength = numbers.push();
console.log('New length of array : ' + newLength);
console.log(numbers);
If no element(s) is passed to push(), the array remains unchanged, and the push() method returns the length of the original array itself.