Javascript Push Pop Shift and Unshift

2020/1/53 min read
bookmark this
Responsive image

This blog show difference between the JavaScript Array's method push, pop, shift and unshift usage. 

Array.prototype.push

Array's push probably is the most commonly used method if you want to add the item to the array,  it will add the new item to the existing array's last item and return the new length. Following the code, you can see that the return is the total length and the existing array had been updated. 

 let x = [1,2,3,4,5];
 let y = x.push(100);

console.log(x)
//  [ 1, 2, 3, 4, 5, 100 ]
console.log(y)
// 6

Use spread syntax (...), the push method support spread syntax, so you can add as this way.

let x = [1,2,3,4,5];
 x.push(100, 200);

console.log(x);
// [1,2,3,4,5,100,200]

Or, if you want to variable is an array and want to use the push and is the same result as above.

 let x = [1,2,3,4,5];
 x.push(...[100, 200])

console.log(x);
// [1,2,3,4,5,100,200]

push is adding to the existing array, but what if I want to add to the new array and keep the existing array no update?

One way is you can use concat as below. You can see the origin x is not updated, but the result concat return is the new array. 

 let x = [1,2,3,4,5];
 let y = x.concat(100);
 let z = x.concat(...[200,300]);

console.log(x);
// [1,2,3,4,5]
console.log(y);
// [1,2,3,4,5,100]
console.log(z);
//[1,2,3,4,5,200,300]

Array.prototype.pop

Pop will remove the last item from the array and return the removed item. 

let x = [1,2,3,4,5];
let y = x.pop();

console.log(x);
// [1,2,3,4]
console.log(y);
// 5

Now, you might want to ask the same question, what if I want to remove the last item but I want to keep the original array and new array. If you need to do that, the following is one way, you can create a new array by using slice().

let x = [1,2,3,4,5];
let z = x.slice();
let y = x.pop();

console.log(x);
// [1,2,3,4]
console.log(y);
// 5
console.log(z);
// [1,2,3,4,5]

Array.prototype.shift

Pop is removed from the last item from the Array, the shift is the opposite, it will be the first item from the array. 

let x = [1,2,3,4,5];
let z = x.shift()

console.log(x);
// [2,3,4,5]
console.log(z);
// 1

Array.prototype.unshift

unshift from the array will add list of value to the beginning of the origin array and return the total length of the origin array. 

let x = [1,2,3,4,5];
let z = x.unshift(100, 200)

console.log(x);
// [100,200,1,2,3,4,5]
console.log(z);
// 7

Conclusion

Now, above are difference of how to use JavaScript's array function, push, pop, shift, unshift.