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.tsx153 chars5 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.tsx162 chars5 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