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"]);