menu

JavaScript/Typescript - 16 Topics

DEEP DIVE INTO

JavaScript/Typescript

Topic:push() method

menu

In JavaScript, the push() method is used to add one or more elements to the end of an array. It modifies the original array by appending the specified values and returns the new length of the array after the addition. Here's the basic syntax of the push() method:

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

  • element1, element2, ..., elementN: The elements you want to add to the end of the array.

Here's an example of how push() works:

javascriptconst fruits = ['apple', 'banana', 'cherry'];

const newLength = fruits.push('date', 'elderberry');

console.log(fruits);      // Outputs: ['apple', 'banana', 'cherry', 'date', 'elderberry']
console.log(newLength);   // Outputs: 5 (the new length of the array)

In this example, the push() method adds the elements 'date' and 'elderberry' to the fruits array, and the new length of the array is returned, which is 5.

You can use the push() method to dynamically add elements to an array, making it a handy way to manage collections of data in JavaScript.

Working Example

1280 x 720 px