The shift() method is used to remove an element/item from the starting point of an array.
The unshift() method is used to add an element/item to the starting point of an array.
Let’s try to add and remove elements from an array using shift() and unshift() methods to understand these methods better.
Note: We will use the browser console to demonstrate examples performed in this post. To open up the browser console:
- Use the F12 key in Chrome and other chromium-based browsers.
- Use CTRL + SHIFT + K keyboard shortcut keys for Mozilla.
- Use Option + ⌘ + C keyboard shortcut keys in Safari (if developer menu does not appear, then open Preferences by pressing ⌘ +, and in Advanced tab check “Show Develop menu in menu bar”).
Suppose we have an array of numbers and we want to remove the first element from it. The code from removing an element from the beginning of the array would go like this:
intArr.shift(); // returns the removed item
Similarly, if we want to add an element at the start of an array, the code for adding an element would go like this:
intArr.unshift(23); // returns the new array length