JavaScript push() method


The push() method in JavaScript is used to add one or more elements to the end of an array. It modifies the original array in place and returns the new length of the array.

Syntax:

array.push(element1, element2, ..., elementN)
  • element1, element2, ..., elementN: The elements you want to add to the array.

Return Value:

  • Number: The new length of the array after the elements have been added.

Key Points:

  • Mutates the original array: The push() method alters the original array.
  • Can add multiple elements: You can push multiple elements at once by passing them as separate arguments.

Example 1: Pushing one element to the array

let fruits = ['apple', 'banana']; let newLength = fruits.push('orange'); console.log(fruits); // ['apple', 'banana', 'orange'] console.log(newLength); // 3 (new length of the array)

Example 2: Pushing multiple elements at once

let numbers = [1, 2, 3]; numbers.push(4, 5, 6); console.log(numbers); // [1, 2, 3, 4, 5, 6]

Example 3: Using push() with an empty array

let list = []; list.push('item1', 'item2'); console.log(list); // ['item1', 'item2']

Performance Consideration:

  • Time complexity: The time complexity of push() is O(1), meaning it adds elements in constant time (if no resizing of the array is required).

Summary:

  • push() is used to append elements to the end of an array, modifying the original array in the process. It returns the updated length of the array and can add one or more elements in a single call.