Mutations - Not sure why my code works

Mutations - Not sure why my code works
0

#1

I managed to solve the problem, but only after removing the else condition in my if loop. All of the test cases passed except when [“hello”, “hey”] was passed into the function.

Why does this work:

function mutation(arr) {
 
 var matchString = arr[0].toLowerCase();
 var refString = arr[1].toLowerCase();
 
  
  for (var i = 0; i < refString.length; i++){
    if (matchString.indexOf(refString[i]) === -1){
      return false;
    } 
  }
    return true;
}
mutation(["hello", "hey"]);

But not this:

function mutation(arr) {
 
 var matchString = arr[0].toLowerCase();
 var refString = arr[1].toLowerCase();
 
  
  for (var i = 0; i < refString.length; i++){
    if (matchString.indexOf(refString[i]) === -1){
      return false;
    } else {
      return true;
     }
  }
}
mutation(["hello", "hey"]);

I’m so confused as to what is semantically different between these two functions. Thanks for your input!

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:57.0) Gecko/20100101 Firefox/57.0.

Link to the challenge:


#2

In the second solution which does not pass all of the tests, the for loop only makes it through one iteration before you either return true or false. Remember, that once a return statement is executed, the function is exited the value specified is returned and NOTHING else happens. The for loop stops iterating, because the return statement was used.

In the first solution above, you loop through the string until you find a situation where matchString.indexOf(refString[i]) === -1 evaluates to true. Once that happens, your solution returns false and immediately exits the function. If the for loop completes iteration of the entire string, that means a situation never was seen where matchString.indexOf(refString[i]) === -1 was true. Then, you simply return true and the function exits.


#3

I hadn’t considered that, but it seems so obvious now that you’ve explained it. Thanks so much for the feedback!