102 of 264 menu

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

array.push(element, element, element...);

Example

Let's add two more elements to the end of an array:

let arr = ['a', 'b', 'c', 'd', 'e']; arr.push('1', '2'); console.log(arr);

The code execution result:

['a', 'b', 'c', 'd', 'e', '1', '2']

Example

We add two new elements to an array and output the new array length:

let arr = ['a', 'b', 'c', 'd', 'e']; let length = arr.push('1', '2'); console.log(length);

The code execution result:

7

Example . Usage

Let's fill an array with numbers from 1 to 9:

let arr = []; for (let i = 1; i <= 9; i++) { arr.push(i) } console.log(arr);

The code execution result:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

See also

  • the unshift method
    that adds elements to the beginning of an array
  • the shift and pop methods
    that remove elements from an array
  • the fill method
    that fills an array
byenru