Master Unshift JavaScript: 3 Pro Tips and Hacks!

November 19, 2023
Master Unshift JavaScript: 3 Pro Tips and Hacks!
Table of Contents
  • Understanding unshift() in JavaScript
  • Using shift() and unshift()
  • push() vs unshift()
  • reverse() vs unshift()
  • Browser Compatibility

In JavaScript, arrays are used to store multiple values in a single variable. It's a complex data type that allows us to store multiple values as a single entity. There are many methods to manipulate these arrays and today, we're going to focus on the unshift() method.

1var fruits = ["Banana", "Orange", "Apple", "Mango"];
2fruits.unshift("Lemon","Pineapple");

Understanding unshift() in JavaScript

The unshift() method in JavaScript adds new items to the beginning of an array, and returns the new length. Unlike the push() method which appends elements to the end of an array, unshift() prepends elements to the start.

1var numbers = [1, 2, 3];
2numbers.unshift(0); // returns 4, numbers will be [0,1,2,3]

Using shift() and unshift()

The shift() method works in the opposite way to unshift(). It removes the first item from an array and returns that removed element. This method changes the length of the array.

1var numbers = [1, 2, 3];
2var firstNumber = numbers.shift(); // returns 1, numbers will be [2,3]

push() vs unshift()

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

1var numbers = [1, 2, 3];
2numbers.push(4); // returns 4, numbers will be [1,2,3,4]
3numbers.unshift(0); // returns 5, numbers will be [0,1,2,3,4]

reverse() vs unshift()

The reverse() method in JavaScript reverses the order of the elements in an array. unshift(), on the other hand, adds one or more elements to the beginning of an array and returns the new length of the array.

1var numbers = [1, 2, 3];
2numbers.reverse(); // returns [3,2,1]
3numbers.unshift(0); // returns 4, numbers will be [0,3,2,1]

Browser Compatibility

All these methods are compatible with all modern browsers, and IE6 and up. For more information, you might find this MDN web docs useful.

You can learn more about JavaScript arrays in our JavaScript course.

Related courses

1 Course

Javascript Fundamentals Course

Javascript Fundamentals

4.7+
834 reviews

Stay Ahead with Code highlights

Join our community of forward-thinkers and innovators. Subscribe to get the latest updates on courses, exclusive insights, and tips from industry experts directly to your inbox.

3D Letter

Related articles

124 Articles

Start learning for free

If you've made it this far, you must be at least a little curious. Sign up and grow your programming skills with Code Highlights.

Start learning for free like this happy man with Code Highlights