Mutations, can't understand

Tell us what’s happening:
Hey guys. My function doesn’t work. Is it because in if-statement i wrote return ? And after first cicle it exits and returns value for first element? How can i check all elements ?

Your code so far


function mutation(arr) {
  let x = arr[1].toLowerCase().split("");
  let y = arr[0].toLowerCase();
  
  for ( let i = 0; i < x.length; i++ )  {
    if ( y.indexOf(x[i])  !== -1 )  {     
      return true;
    }
      return false;
   }
}
mutation(["hello", "fgg"]);

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/mutations/

i think what your code is doing right now is this:

for each letter in x {
  if the first letter of x is found in y then {
      exit with true
  } otherwise {
      exit with false;
  }
}

So obviously your code returns false if the first letter of x doesn’t match and true if the first letter of x does match a letter in y.

As you mentioned , this doesn’t satisfy the challenge because you need to check every letter in x, not just the first.

So instead of returning true when the first letter is good, allow the loop to do its job and continue checking.

so perhaps something like this:

for ( let i = 0; i < x.length; i++ )  {
    if ( y.indexOf(x[i])  === -1 )  {     
      return false;
    }
 }
return true;

I’m not really a fan of return statements inside of for loops but anyway, something like the above should work.
I would also suggest using something more descriptive than ‘x’ and ‘y’ in your code.

hope this helps.

2 Likes

One of these things is not like the other.

**Thanks a lot. It helps me :slight_smile: *

sorry i know, this code is part other decision. I solved it via mmethod every(); but i want to solve this exercise via loop-for and i stuck. Main thing was understanding how works loop-for in that situation