SoFunction
Updated on 2025-04-10

A brief analysis of the understanding of unshift and push methods in JS

Please tell me the understanding of the unshift and push methods in js

In JavaScript,unshiftandpushare two commonly used methods of arrays, which are used to add elements at the beginning and end of an array respectively. Both methods are methods to change the original array, which means that they will directly modify the original array rather than create a new array.

  • push method

pushThe method adds one or more elements to the end of the array and returns the new array length. For example:

let arr = [1, 2, 3];
let length = (4, 5);
(arr);  // Output: [1, 2, 3, 4, 5](length);  // Output: 5,Because the new length of the array is5

In this example,pushMethods add 4 and 5 to the arrayarrend and return the new array length 5.

  • unshift method

unshiftThe method adds one or more elements to the beginning of the array and returns the new array length. For example:

let arr = [1, 2, 3];
let length = (0, -1);
(arr);  // Output: [-1, 0, 1, 2, 3](length);  // Output: 5,Because the new length of the array is5

In this example,unshiftMethods add -1 and 0 to the arrayarrstarts with   and returns the new array length 5.

Summarize

  • pushandunshiftAll are methods to change the original array.
  • pushAdd elements at the end of the array, andunshiftAdd elements at the beginning of the array.
  • Both methods return the new array length.

This is the article about this article about the unshift and push methods in js. For more related contents of js unshift and push methods, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!