With the shift and unshift methods I remove and add respectively an element at the beginning of each array in JavaScript.
The syntax of these methods is as follows:
array.unshift (element1, element2,…, elementN)
array.shift()
As we can see with the unshift method it is possible to insert more than one element between round brackets, separated by commas.
JavaScript shift and unshift – example 1
Create an array of elements and add an element, inserted through a dialog box, at the head of the array.
So let’s assume we have our array of school items as always:
var objectsSchool = ['eraser', 'notebook', 'pencil'];
Then we ask the user to enter an element:
var objectNew = prompt('Insert a school object');
We therefore decide to insert it at the top of the array with the unshift method:
objectsSchool.unshift(objectNew);
console.log(objectsSchool);
In this case, in the console we will see as the first element the one entered by the user.
Now we delete the same element that the user has chosen to insert.
We will need to use the shift method:
objectsSchool.shift();
console.log(objectsSchool);
In the browser console, the first list will be displayed without the item entered by the user.
JavaScript shift and unshift – example 2
Let’s take an example using the days array that we have already used in the previous examples.
This time, however, we will remove the days at the beginning of the array, so starting from Monday.
Try clicking on the button below to get the effect:
Here is the complete code used to solve this simple algorithm that uses the shift () method to delete elements at the beginning of the array.
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
function removeDay() {
days.shift();
alert ("I took off a day");
// I print every day
for (var i = 0; i < days.length; i ++) {
alert(days[i]);
}
}
After in the html page I insert the following code:
<input type="submit" value="Remove a day" onClick="removeDay()">
Likewise I use unshift () to add elements to the beginning of the array.
Here is a simple example:
var days = ["Monday"];
days.unshift("Tuesday");
Conclusion
Of course these are just simple examples of the JavaScript shift and unshift methods, useful for getting started with arrays in JavaScript. In the next few lessons we will address other methods.