JavaScript shift and unshift Methods Explained
JavaScript shift and unshift let you remove or add items at the start of an array. See how both methods work, what they return, and when to reach for them.


What Are JavaScript SHIFT and UNSHIFT and How Are They Used?
In the previous Javascript ARRAY, POP, PUSH, LENGHT article, if you remember the array usage I explained, we created an array named sepet and added a few elements to it. Using the same example again, you’ll learn what the Javascript Shift and Javascript Unshift functions are and how to use them.
In JavaScript, the Shift and Unshift functions are important methods that work on arrays. The Shift method removes the element at the beginning of the array and shifts the other elements one position forward. The Unshift method adds one or more elements to the beginning of the array.
Javascript SHIFT
The Javascript Shift function returns the first element of the array. In other words, whichever element has the smallest index number (0) is the one that will be returned. Let’s try it now with the example below.
let sepet= ["elma", "armut", "portakal","nane","muz"];
console.log(sepet.shift());
Javascript UNSHIFT
The Javascript unshift function adds an element to index 0 of the sepet array so that it becomes the first element. If you want to add a new element to the very beginning of an array, you can use UNSHIFT.
let sepet= ["elma", "armut", "portakal","nane","muz"];
sepet.unshift('kivi');
console.log( sepet);
// You will see the following result in the console.
["kivi","elma","armut","portakal","nane","muz"]
The Shift and Unshift methods are used to remove or add elements at the beginning of an array. These methods let you perform operations on arrays efficiently and quickly.
- Mozilla Developer Network (MDN): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
- W3Schools: https://www.w3schools.com/jsref/jsref_shift.asp
Share it if it helped


