Javascript Array Methods: shift() and unshift()

JavaScript Array Methods — in this article we will learn about 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()


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.


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

When an array is empty

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


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

console.log(array);
//OUTPUT: ["B"]

firstElement= array.shift();
console.log(firstElement);
//OUTPUT: B

console.log(array);
//OUTPUT: []

firstElement= array.shift();
console.log(firstElement);
//OUTPUT: undefined;

console.log(array);
//OUTPUT: []

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.


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

Array unshift() method.

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


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

console.log(array);
//OUTPUT: ["X", "A", "B", "C", "D"]

newLength= array.unshift("Y","Z");
console.log(newLength);
//OUTPUT: 7

console.log(array);
//OUTPUT: ["Y", "Z", "X", "A", "B", "C", "D"]

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.

I hop you like this Javascript Array Methods: shift() and unshift() article.


Also Read: