Free UI Resources - UI Dev Made Easy
Javascript

Javascript Array Methods – .push()

.push()

The .push() method is a built-in function in JavaScript that allows you to add one or more elements to the end of an array. It’s a simple and efficient way to append new items to the existing array.

Here’s the basic syntax of the .push() method:

array.push(element1, element2, ...);
  • element1, element2, etc.: The elements you want to add to the end of the array.

The .push() method doesn’t return a new array; it modifies the original array by adding the specified elements to the end. The method then returns the new length of the array after the elements have been added.

Here’s an example to illustrate how .push() works:

const colors = ['red', 'green', 'blue'];

const newLength = colors.push('orange', 'yellow');

console.log(colors);      // Output: ['red', 'green', 'blue', 'orange', 'yellow']
console.log(newLength);   // Output: 5 (length of the updated array)

In this example, the .push() method adds the strings 'orange' and 'yellow' to the end of the colors array, resulting in a new length of 5.

You can also use .push() to add a single element:

const numbers = [1, 2, 3];

numbers.push(4);

console.log(numbers); // Output: [1, 2, 3, 4]

Keep in mind the following points when using .push():

  1. Modifies Original Array: The .push() method modifies the original array in-place. It doesn’t create a new array.
  2. Order: The elements will be added to the end of the array in the order they are specified.
  3. Return Value: The .push() method returns the new length of the array after the elements are added.
  4. Appending Multiple Elements: You can use .push() to append multiple elements at once by separating them with commas.
  5. No Limit: There’s no fixed limit to the number of elements you can push onto an array, but very large arrays can impact performance.
  6. Mutability: Since .push() modifies the original array, if you need to create a new array with the added elements, consider using the spread operator or the .concat() method.

In summary, the .push() method is a simple and effective way to add elements to the end of an array. It’s commonly used to dynamically update arrays with new data or elements.

back to top