Javascript has methods to add or remove elements from the array.
push and unshift are main methods to add elements from the array and pop and shift are main methods to remove elements from the array.
The four methods are both destructive, so they can change the original array. Also, they rely on the length of array, so they find a place where to put or remove element.
There is a big difference between push,pop and shift,unshif.
push and pop are used to manipulate element at the end of the array.
But, shift and unshift are used to manipulate element at the beginning of the array.
let sports = ['basketball','baseball','hockey'];
sports.push('soccer');
alert(sports); // basketball,baseball,hockey,soccer
let sports = ['basketball','baseball','hockey', 'soccer'];
sports.pop();
alert(sports); // basketball,baseball,hockey
let sports = ['basketball','baseball','hockey'];
sports.shift();
alert(sports); // basketball,baseball
let sports = ['basketball','baseball'];
sports.unshift('hockey');
alert(sports); // basketball,baseball,hockey
Rather than using shift and unshift, using push and pop is more efficient and faster way to get the result.
For example, this is how shift method work!
- Find an element which is index of 0 and remove the element
- Move all the elements to left. Therefore, all the elements' index are changed.
unshift method work same way as shift method.
However, pop and push method don't change any order or index of elements and only manipulate element at the end of array.