Mutations solution, please explain! :)

Mutations solution, please explain! :)
0

#1

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;
 }

#2

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.


#3

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?


#4

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

It has nothing to do with assigning the array elements to variables. It is fine to use arr[0] and arr[1]. The problem is your function returns either true or false during the 1st iteration of the for loop depending on the evaluation of arr[0].indexOf(arr[1][i].toLowerCase()) === -1. Remember, that once a return statement is executed, the function is immediately exited. That means, even if the for loop was not finished, a value is returned and then nothing else happens. You will notice in the FCC solution, that the return true; is outside the for loop, which is the biggest difference between your’s and FCC’s (other than the other issue which @joesmith100 mentioned above).


#5

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