Search code examples
javascriptcoercion

Javascript - Is passing array[0] directly vs array[0] by i= 0 array[i] fundementally different inside an "if" statement?


Working on a programming challenge. The objective is to create a function that "Drop[s] the elements of an array (first argument), starting from the front, until the predicate (second argument) returns true."

dropElements([1, 2, 3, 4], function(n) {return n > 5;});

function dropElements(arr, func) {
    for (i = 0; i < arr.length-1; i++) {
        if(func(arr[i])) {
            break;
        }
        else { 
            arr.splice(i,1);
            i--;
        }
    }
    return arr; 
}

returns [4] which is the incorrect answer

However the following:

dropElements([1, 2, 3, 4], function(n) {return n > 5;});

function dropElements(arr, func) {
    for (i = 0; i < arr.length; i++) {
        if (func(arr[0])) {
            break;
        } 
        else {
            arr.shift();
            i--;
        }
    }
    return arr; 
}

returns [] which is the correct answer

I wrote it all out by hand and it looks like it should out put the same. Is it something to do with coercion that I don't understand?


Solution

  • Your first loop is up to arr.length-1 while the second is arr.length.