javascript array push

Javascript Array Push

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

Syntax:


arr.push(element1, element2, ..., elementN)
  

Here, arr is the array on which the push operation is being performed, and element1, element2, ..., elementN are the elements that need to be added to the end of the array.

The push method modifies the original array and returns the new length of the array.

Example:


let myArray = ['apple', 'banana', 'orange'];
let length = myArray.push('grapes');

console.log(myArray); // Output: ['apple', 'banana', 'orange', 'grapes']
console.log(length); // Output: 4
  

The above code adds a new element 'grapes' to the end of the myArray, and then logs the new array and its length.

Multiple Ways:

  • We can also use the spread operator to add elements to an array:

let myArray = ['apple', 'banana', 'orange'];
myArray = [...myArray, 'grapes'];

console.log(myArray); // Output: ['apple', 'banana', 'orange', 'grapes']
    
  • Another way to add elements to an array is by using the concat() method:

let myArray = ['apple', 'banana', 'orange'];
let newArray = myArray.concat(['grapes']);

console.log(myArray); // Output: ['apple', 'banana', 'orange']
console.log(newArray); // Output: ['apple', 'banana', 'orange', 'grapes']
    

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe