How to Delete the First Element of an Array in JavaScript?

Estimated read time 1 min read

You can delete the first element of an array in JavaScript using the shift() method. Here’s an example:

const myArray = [1, 2, 3, 4];
myArray.shift(); // removes the first element
console.log(myArray); // [2, 3, 4]

In this example, we first create an array myArray with four elements. We then call the shift() method on the array, which removes the first element of the array and shifts all the remaining elements one position to the left. Finally, we log the resulting array to the console, which shows that the first element has been removed.

Note that the shift() method modifies the original array in place, so if you need to preserve the original array, you should make a copy of it before calling shift(). You can make a copy of an array using the spread operator like this:

const myArray = [1, 2, 3, 4];
const myArrayCopy = [...myArray];
myArrayCopy.shift(); // removes the first element
console.log(myArrayCopy); // [2, 3, 4]
console.log(myArray); // [1, 2, 3, 4]

In this example, we first create a copy of the original array myArray using the spread operator. We then call shift() on the copy, which removes the first element. The original array myArray is left untouched.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply