Shouldn't this work? Re: Mutations Algorithm Challenge

See comments in code; I put the values passed in for testB[i] to help me understand how the loop works. In this case, testB[2] = “y” and when passed to testA.indexOf, it should === -1 and return false. This, however, doesn’t pass the challenge.

I know the correct solution to pass the challenge is to return false inside of the loop if === -1 and return true outside of the for loop if not. Shouldn’t the code below pass, since it’s essentially the same except that I’m using an else statement and returning inside of the loop, or am I missing something?


function mutation(arr) {
var testA = arr[0].toLowerCase();
var testB = arr[1].toLowerCase();
 
for(i = 0; i < testB.length; i++) {
  if(testA.indexOf(testB[i]) != -1) {
    //hello.indexOf(h) === 0
    //hello.indexOf(e) === 1
    //hello.indexOf(y) === -1 => should return false
    return true;
  } else {
    return false;
    }
}
}


mutation(["hello", "hey"]);

The code that passes:


function mutation(arr) {
var testA = arr[0].toLowerCase();
var testB = arr[1].toLowerCase();
 
for(i = 0; i < testB.length; i++) {
  if(testA.indexOf(testB[i]) === -1) {
    //hello.indexOf(h) === 0
    //hello.indexOf(e) === 1
    //hello.indexOf(y) === -1
    return false;
  } 
}
    return true;
}


mutation(["hello", "hey"]);

Then, shouldn’t this return false, since return is now outside of the for loop? I must not understand for loops completely. Since in this example, arr[1] = "yeh" and arr[1][0] = "y", shouldn’t it exit the for loop at the very first iteration and return false?

function mutation(arr) {
  var testA = arr[0].toLowerCase();
  var testB = arr[1].toLowerCase();
  
  for(i = 0; i < testB.length; i++) {
    if(testA.indexOf(testB[i]) != -1) {
      //hello.indexOf(y) === -1
      //hello.indexOf(e) === 1
      //hello.indexOf(h) === 0
      return true;
    } 
  }
  return false;
}

mutation(["hello", "yeh"]);