Manipulating Arrays with the shift() and unshift() Methods

Guest Posts Paolo Nikko Nuñal

If you have been following our previous articles you might notice that we have discuss about the push() and pop() methods with arrays. In which new items will be added or remove at the end of the array. This time around, you can also add and remove elements on the first index on the array. You can do this with the shift() and unshift() methods.

Code


<script>
    var dataArray = new Array("John","Joe","Joseph");
    dataArray.unshift("Jay");
    alert(dataArray);
</script>


From the code above we have inserted the string "Jay" on the first index of the array. In which it will output "Jay","John","Joe","Joseph" or in short it is placed at index[0]. On the other hand the shift() method removes the first index of the array. It also changes the length of the array.

Code


<script>


 var dataArray = new Array("John","Joe","Joseph");
    dataArray.shift();
    alert(dataArray);
</script>


In the example above, the shift() method removes the first item on the array or index(0) and returns that method. You can use this if you want to get the first element of the array without having to iterate using for loops. The shift() function can automatically get the first item on the array easily.