العودة إلى الدورة

Removing Elements: pop() and shift()

JavaScript: الدورة الكاملة للمبتدئين من 'الصفر إلى الاحتراف'

55. Removing Elements from Arrays

We use .pop() and .shift() to remove elements from the ends of an array.

1. .pop(): Removing from the End

The pop() method removes the last element from an array and returns that removed element.

javascript const stack = ['A', 'B', 'C'];

let lastItem = stack.pop(); // lastItem is 'C'

console.log(stack); // ['A', 'B'] console.log(lastItem); // C

2. .shift(): Removing from the Beginning

The shift() method removes the first element from an array and returns that removed element. Like unshift(), this requires re-indexing and is slower for very large arrays.

javascript const list = ['task 1', 'task 2', 'task 3'];

let nextTask = list.shift(); // nextTask is 'task 1'

console.log(list); // ['task 2', 'task 3']

.splice() (Preview)

For removing elements from the middle of an array, or removing a specific number of elements, we use the powerful .splice() method (covered later in advanced array lessons).