Very basic If statements I can´t understand why this works like THIS

So I´m trying to do the challenge https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/drop-it and I´m doing some tests.

By now I´m trying to see if i can make it work by putting manually the condition, here´s what I´m doing:

function dropElements(arr, func) {

    for(number in arr){
      if (arr[number] === 1){
        return arr
      }
      else{
        arr.shift()
      }
    }
    return arr
}

dropElements([0, 1, 0, 1], function(n) {return n === 1;})

Please explain me this:
In the first iteration, arr[0] is equal to 0, so When the engine reaches the line arr[number] === 1 that is not true, so goes to the else statement and does arr.shift()
So here it comes what i dont understand, in the second iteration, arr[1] is equal to 1, so When the engine reaches the line arr[number] === 1 that is true. So it just should return arr (which at that point is[1,0,1] ) because in the first iteration JS did the arr.shift() line

However, it doesn´t return that, it returns [0,1] please enlighten me why :flushed:

First, make sure you declare your number variable with let keyword.

when you call .shift it will remove the first item in the array. Notice you have two number 1s in your array and your array looks like [0, 1, 0, 1]. In your if statement, you are matching with 1s which means you will remove the first two items in the array, resulting [0, 1] in the end.

1 Like

To expand on what @shimphillip said:

As you are mutating your array (removing first element), the number of properties in your array changes, so arr[number] ends up pointing to a value you didn’t expect. On first iteration we check the property of 0, whose value is 0, and so first element gets removed. On second iteration we check property of 1, and behold! arr[1] now points to 0 since your array was modified earlier, and thus shift() removes the first element once again (1). On third iteration…well there is no third iteration because our array now shrunk to just 2 properties: 0 and 1, and we already checked those. So arr is returned as [0, 1].

Hope that helps.

1 Like

Ohhhh rigtht! Ha how could I didn´t see that. Thanks. Well going back to see if i can make it work now hehe