push method
The push method adds an
unlimited number of elements to
the end of an array. In this case,
the original array is modified,
and the new length of the array
is returned as a result.
Syntax
javascriptarray.push(element, element, element...);
Example
Let's add two more elements to the end of an array:
javascriptlet arr = ['a', 'b', 'c', 'd', 'e'];
arr.push('1', '2');
console.log(arr);
The code execution result:
javascript['a', 'b', 'c', 'd', 'e', '1', '2']
Example
We add two new elements to an array and output the new array length:
javascriptlet arr = ['a', 'b', 'c', 'd', 'e'];
let length = arr.push('1', '2');
console.log(length);
The code execution result:
javascript7
Example . Usage
Let's fill an array with numbers
from 1 to 9:
javascriptlet arr = [];
for (let i = 1; i <= 9; i++) {
arr.push(i)
}
console.log(arr);
The code execution result:
javascript[1, 2, 3, 4, 5, 6, 7, 8, 9]