What is the difference between unshift() and Push() method in JavaScript?


Both unshift() and push() are methods in JavaScript that are used to add elements to an array. However, there are some differences between them:

  • push() method: The push() method adds one or more elements to the end of an array and returns the new length of the array. It modifies the original array.

Example:

let arr = [1, 2, 3];
arr.push(4);
console.log(arr); // Output: [1, 2, 3, 4]
  • unshift() method: The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array. It also modifies the original array.

Example:

let arr = [1, 2, 3];
arr.unshift(0);
console.log(arr); // Output: [0, 1, 2, 3]

So, the main difference between push() and unshift() is the position where the new elements are added. push() adds elements to the end of the array, while unshift() adds elements to the beginning of the array.

Another difference is that push() can add multiple elements at once, separated by commas, while unshift() can also add multiple elements, but they need to be passed as separate arguments.

Example:

let arr = [1, 2, 3];
arr.push(4, 5);
console.log(arr); // Output: [1, 2, 3, 4, 5]

arr.unshift(-1, 0);
console.log(arr); // Output: [-1, 0, 1, 2, 3, 4, 5]

In summary, push() adds elements to the end of an array, while unshift() adds elements to the beginning of an array. Both methods modify the original array and return the new length of the array.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.