shift() removes the first element from a JavaScript array and returns the removed value. It mutates the original array, decreases length, and moves the remaining values to lower indexes.
const scripts = ["PHP", "ASP", "JavaScript", "HTML"];
const removed = scripts.shift();
console.log(removed); // PHP
console.log(scripts); // ["ASP", "JavaScript", "HTML"]
const firstElement = array.shift();
shift() does not accept an index. It always removes index 0.
Unlike pop(), removing from the beginning requires the remaining values to take new numeric indexes.
const scripts = ["PHP", "ASP", "JavaScript", "HTML"];
scripts.shift();
for (const [index, value] of scripts.entries()) {
console.log(index, value);
}
0 ASP
1 JavaScript
2 HTML
const values = [];
console.log(values.shift()); // undefined
console.log(values.length); // 0
Add at the end with push() and remove from the beginning with shift() for a simple first-in, first-out queue.
const queue = [];
queue.push("first");
queue.push("second");
queue.push("third");
console.log(queue.shift()); // first
console.log(queue.shift()); // second
const values = [1, 2, 3, 4];
while (values.length > 2) {
console.log(values.shift());
}
console.log(values); // [3, 4]
If you need to remove a known block of several leading values at once, splice() or a non-mutating slice() operation may express the intent more clearly.
const scripts = ["PHP", "JavaScript", "Python"];
console.log(scripts[0]); // PHP
console.log(scripts.length); // 3
shift() changes the indexes of remaining elements. If an application repeatedly removes from the front of a very large collection, consider whether a queue design using a moving index or another data structure better fits the workload. For ordinary small arrays, clarity usually matters more than premature optimization.
const original = [1, 2, 3];
const withoutFirst = original.slice(1);
console.log(original); // [1, 2, 3]
console.log(withoutFirst); // [2, 3]
shift() to return the remaining array instead of the removed value.shift() when you only need to inspect array[0].Add at the Beginning with unshift() Remove from the End with pop() Remove by Position with splice() Display Array Elements Array Reference
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.