0

I wanted to delete the first and third elements of the array using the forEach method. I was able to do this, but the question came to me: Why are elements deleted in forEach registered in the console but elements that were not deleted are not registered in the console?

Does not the forEach method apply to all elements of a functional array? So why aren't all the array elements registered in the console?

const cartItems = ['Book1', 'Book2', 'Book3', 'Book4']

cartItems.forEach(function (item, index, array) {

    // I mean console.log below 👇

    console.log(item)

    if (index == 0) {
        array.shift()
    }

    if (index == 1) {
        array.splice(1, 1)
    }
})

console.log(cartItems)
1
  • 1
    Because shift() and splice() mutate the original array. Commented Jun 19, 2021 at 11:03

2 Answers 2

3

In a nutshell, it's not a good idea to modify the array walked over by forEach (or any other iterative function). Here's a telling quote from MDN docs:

The range of elements processed by forEach() is set before the first invocation of callbackFn. Elements which are assigned to indexes already visited, or to indexes outside the range, will not be visited by callbackFn.

In your example, the callback function of forEach is skipped for 'Book2' item because array.shift essentially reassigns it to index 0 (which has already been visited). The same thing happens with 'Book4' after array.splice.

Sign up to request clarification or add additional context in comments.

Comments

1

You must notice the definition of shift and splice method. Based on this the definition of shift is:

The shift() method removes the first item of an array.

Note: This method changes the length of the array.

Note: The return value of the shift method is the removed item.

Note: This method will change the original array.

And the same as splice method is:

The splice() method adds/removes items to/from an array, and returns the removed item(s).

Note: This method changes the original array.

And the answer for your question why aren't all the array elements registered in the console? is that both methods change the original array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.