The Mysterious .shift() & .unshift()

Prasham Ashesh
3 min readOct 10, 2019

--

Javascript Array’s functions, push and pop is intuitive, but shift and unshift are not.

Push and pop are simple they treat that array as a stack, and the last element is considered to be top of the stack. So, whenever a push and pop is performed its performed on top of the stack,i.e. at end of the array.

push()
let x = [1,2,3,4,5]
x.push(6) //returns the length of the new array -> 6
console.log(x) //[1,2,3,4,5,6]
x.pop() //returns the popped element of the array -> 6
console.log(x) //[1,2,3,4,5]
pop()

Whereas, shift and unshift, assume the first element of the array to be the top of the stack.

shift() and unshift() are just pop and push, applied on a reversed Stack.

Now, if any noob(like me) would see it his/her perception would be to assume that push and pop are for arrays assumed as a stack(LIFO), whereas shift() and unshift() are for arrays assumed as Queue (FIFO)

let x = [1,2,3,4,5]
x.noobShift(6) //would have returned the length of the new array -> 6
console.log(x) //[6,1,2,3,4,5]
x.noobUnshift() //returns the dropped element of the array -> 5
console.log(x) //[6,1,2,3,4]
//noobShift & noobUnshift is how I assumed the JavaScript's shift() and unshift() function to work.

But, that’s not the case, I was picturing it all wrong in my head.

How .shift() should be pictured:

x=               [1,2,3,4]
x.shift() <-shift the array by one place to the left
1[2,3,4] <= the new state of Array with 1 out of place
x.shift() returns 1, and x becomes [2,3,4]
shift()

How .unshift() should be pictured:

x=               [1,2,3,4]
x.unshift(0) -> shift the array by one place to the rigt
0[1,2,3,4] <= the new state of Array with 0 ready to be inserted
x.unshift() returns 5, the length of updated array, and x becomes [0,1,2,3,4]
unshift()

I have always felt that visualizing a concept, helps create a better picture. After all, “If a picture is worth a thousand words, a video is worth millions”, at least. Hope, this helps.

--

--