JavaScript Code

JavaScript Array push()


push() – Add Element to Array

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

1. 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


Copyright @2022