Mutations solution, please explain! :)

Hi I was wondering why this solution didnt work for the mutations challenge - I looked at the solution and was almost exactly the same as the basic one proposed, I just didnt create two new variables to hold arr[1] and arr[2]. I’m not sure what I’m missing here, can anyone explain?

my solution:

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

freecodecamp solution:

function mutation(arr) {
  var test = arr[1].toLowerCase();
  var target = arr[0].toLowerCase();
  for (i=0;i<test.length;i++) {
    if (target.indexOf(test[i]) === -1)
      return false;
  }
  return true;
 }

Hi @sbkmkb

Your solution isn’t working because you’re only checking the first letter of the second string rather than all of the letters.

if (...) 
  return true; 
else 
  return false;

This will cause the function to return after the first loop.

You want to do what the freecodecamp solution and does and only return true after the loop has finished when all letters have been checked.

Hi joesmith, thanks for your reply!
This is what confuses me actually. I dont get how the basic solution isn’t returning after the first iteration like mine is. I thought that our solution structures are exactly the same with the only difference being that I havent made new variables to hold arr[0].toLowerCase() and arr[1].toLowerCase(). Is this difference what makes the loop cycle through all the iterations before returning or am I missing something else?

oh wow, right… I didnt get it the first time around but I see where I was misunderstanding. This always confused me about for loops, i think I’m finally understanding them correctly. Thank you so much! I’ll make sure to correctly format my posts next time