Removing an element from the first position

To remove a value from the beginning of the array, we can use the following code:

for (let i = 0; i < numbers.length; i++) { 
  numbers[i] = numbers[i + 1]; 
} 

We can represent the previous code using the following diagram:

We shifted all the elements one position to the left. However, the length of the array is still the same (17), meaning we still have an extra element in our array (with an undefined value). The last time the code inside the loop was executed, i+1 was a reference to a position that does not exist. In some languages, such as Java, C/C++, or C#, the code would throw an exception, and ...

Get Learning JavaScript Data Structures and Algorithms - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.