When we work in any programming language, arrays play an essential role in fulfilling programming tasks. In javascript, arrays store the same data types, like strings, integers, arrays, or even functions.
While working with arrays, we often need to add or remove elements in an array. For fulfilling this need, shift() and unshift() methods come to the rescue. In this post, we will have a brief discussion about shift() and unshift() functions in JavaScript and a couple of examples to have a profound understanding of these functions.
What are Shift() and Unshift() methods in JavaScript
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”).
How to use shift() method in JavaScript
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
console.log(intArr);
How to use unshift() method in JavaScript
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
console.log(intArr);
Conclusion
The shift() method in JavaScript removes an item from the beginning of an array and shifts every other item to the previous index, whereas the unshift() method adds an item to the beginning of an array while shifting every other item to the next index. The returning value of the shift() method is the item that is removed from the array, and the unshift() method returns the new length of the array. These two methods are used a lot when working with arrays in JavaScript. In this post, we have discussed what shift() and unshift() methods are in JavaScript and how to use them.
from https://ift.tt/2W1Vacv
0 Comments