Passing all tests except one in Mutations challenge

Tell us what’s happening:
Hi guys, I don’t know what I’m missing here. I’m passing all tests except:

mutation(["hello", "hey"]); which returns true instead of false.

Thank you!

Your code so far


function mutation(arr) {
var firstWord = arr[0].toLowerCase().split("");
var secondWord = arr[1].toLowerCase().split("");
for (var i = 0; i < secondWord.length; i++){
  if (firstWord.indexOf(secondWord[i]) === -1){
    return false;
  } else {
    return true;
  }
}
}

mutation(["hello", "hey"]); //returns true


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0.

Challenge: Mutations

Link to the challenge:

Hello~!

Take a look at your code inside the for loop. On the first iteration, what happens?

Hello~!

Take a look at your code inside the for loop. On the first iteration, what happens?

On the first iteration I’m searching for the existence of secondWord[0] in firstWord. In other words: is "h" in "hello"? Yes it is, so the code moves to de second iteration and then to the third iteration.

Does it move to the second iteration?

 if (firstWord.indexOf(secondWord[i]) === -1){
    return false;
  } else {
    return true;
  }

This is the code in your block. Remember that when a return statement executes, a function ends. :slight_smile:

2 Likes

I don’t understand why you say that the second iteration never happens. Because return false will be executed only when: firstWord.indexOf(secondWord[i]) === -1,

But:
(first iteration) firstWord.indexOf(secondWord[0]) === 0, so the for loop continues

(second iteration) firstWord.indexOf(secondWord[1]) === 1, and the final iteration would be:

(third iteration) firstWord.indexOf(secondWord[2]) === -1 (because there is no “y” in “hello”) and here the function stops.

You’re right that return false will only be executed sometimes, but when it doesn’t, your else statement also has a return statement, which will exit from the function, as @nhcarrigan mentioned above

1 Like

Hi Eric, but that’s exactly what I want, that the functions stops when -1 is found. The thing is -1 is never found until firstWord.indexOf(secondWord[2]). I don’t understand why my iterations apparently aren’t working (but they work for every test except this).

Notice any similarities in the other tests that are supposed to return false?

(They all have the wrong first letter, so it’s okay that the function doesn’t loop, because it doesn’t need to)

The test case that is failing is the only test case where the wrong letter occurs later in the string, and it’s failing because your function isn’t looping.

I’d recommend throwing a console.log inside the loop, and see for yourself that the function isn’t looping.

2 Likes