What is the wrong here?

Tell us what’s happening:

Your code so far


function mutation(arr) {
let val0 = arr[0].toLowerCase();
let val1 = arr[1].toLowerCase();

for (var i = 0; i < val1.length; i++) {
  if (val0.indexOf(val1[i]) < 0) {
    return false;
  } else {
    return true;
  }
}
}


console.log(mutation(["hello", "hey"]));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36.

Challenge: Mutations

Link to the challenge:

return aborts a function. So after the first letter is compared, your code stops.

1 Like

how can i fix that ?

Try moving the return true to a different position. You can stop the loop as soon as you have found one false case, but you need to run through the whole loop (check all characters) before you confirm true.

Hi Ali,

You are one little tweak away from pulling it off! :slight_smile:

The bug is in the for loop. The first part,

if (val0.indexOf(val1[i]) < 0) {
    return false;
  }

is correct. It returns false if it catches a letter that doesn’t match.
However, the second part:

 else {
    return true;
  }

generates a bug. This is because the keyword return stops the for loop. However, we want to loop through all the letters of the word to check that they match, so we shouldn’t stop the loop when the first letter matches. We want to continue the loop to check if the rest of the letters match.

The solution is to take the return true; statement out of the for loop, and place it at the end of the function, so that we can return true once we have looped through all the letters of the word, and not before.

My solution (spoiler alert)
function mutation(arr) {
let val0 = arr[0].toLowerCase();
let val1 = arr[1].toLowerCase();

for (var i = 0; i < val1.length; i++) {
  if (val0.indexOf(val1[i]) < 0) {
    return false;
  }
}
return true;
}