Javascript Array Methods: shift() and unshift()

Javascript Array Methods: shift() and unshift()

Javascript Array Methods: shift() and unshift()

shift() and unshift() are the javascript array methods.

When you want to add or remove an item from the beginning of an array, shift() and unshift() methods will be used.

And when you want to add or remove an item from the end of an array, push() and pop() methods will be used. Read my other article about push() and pop() method. Javascript Array Methods: push() and pop()

Javascript Array: shift() method.

shift() function pulls the first item of the given array and returns it, and removes the first item from the beginning of an array.

<br />var array= ["A", "B", "C", "D"];<br /><br />var firstElement= array.shift();<br /><br />console.log(firstElement);<br />//OUTPUT: A<br /><br /><br />console.log(array);<br />//OUTPUT: ["B", "C", "D"]<br /><br />

When an array is empty

If there is an empty array and if you’ll call shift() the method, it’ll return undefined.

<br />var array= ["A", "B"];<br /><br />var firstElement= array.shift();<br />console.log(firstElement);<br />//OUTPUT: A<br /><br />console.log(array);<br />//OUTPUT: ["B"]<br /><br /><br />firstElement= array.shift();<br />console.log(firstElement);<br />//OUTPUT: B<br /><br /><br />console.log(array);<br />//OUTPUT: []<br /><br /><br />firstElement= array.shift();<br />console.log(firstElement);<br />//OUTPUT: undefined<br /><br /><br />console.log(array);<br />//OUTPUT: []<br /><br />

Here in the above code, you can see that we have called shift() method 3 times and when it is called last time, it returns the value undefined. because there is no item in the array.

Using shift() method in while loop.

<br />var array= ["A", "B", "C", "D"];<br /><br /><br />while( (i = array.shift()) !== undefined ) {<br />    console.log(i);<br />}<br />//OUTPUT: A, B, C, D<br /><br />

Javascript Array: unshift() method.

unshift() function adds one or more item at the beginning of an array and returns a new length of an array.

<br />var array= ["A", "B", "C", "D"];<br /><br />var newLength= array.unshift("X");<br />console.log(newLength);<br />//OUTPUT: 5<br /><br />console.log(array);<br />//OUTPUT: ["X", "A", "B", "C", "D"]<br /><br /><br />newLength= array.unshift("Y","Z");<br />console.log(newLength);<br />//OUTPUT: 7<br /><br />console.log(array);<br />//OUTPUT: ["Y", "Z", "X", "A", "B", "C", "D"]<br /><br />

Note: When multiple items are passed as parameters to unshift() method, they are being inserted in a chunk at the beginning of an array. They are prepended in the right to left order.

Also Read:

Leave a Comment