remove an element from the beginning of an array in javascript

There are at least two ways to remove an element from the beginning of an array in JavaScript: using the shift() method or the splice() method. Both methods modify the original array, which is a mutable data structure in JavaScript.

Here is an example using the shift() method:

index.tsx
let arr = [1, 2, 3, 4, 5]; // [1, 2, 3, 4, 5]
let first = arr.shift();   // 1
console.log(first);        // 1
console.log(arr);          // [2, 3, 4, 5]
153 chars
5 lines

In this example, we declare an array arr with five elements. We then call the shift() method on arr and assign its return value to first. This removes the first element of arr and returns it. Finally, we log both first and arr to the console to show the mutation.

Here is an example using the splice() method:

index.tsx
let arr = [1, 2, 3, 4, 5]; // [1, 2, 3, 4, 5]
let removed = arr.splice(0, 1); // [1]
console.log(removed);      // [1]
console.log(arr);          // [2, 3, 4, 5]
162 chars
5 lines

In this example, we declare an array arr with five elements. We then call the splice() method on arr, providing 0 as the starting index and 1 as the number of elements to remove. This returns an array with the removed elements, which we assign to removed. Finally, we log both removed and arr to the console to show the mutation.

gistlibby LogSnag