Mutations - all good except the first combo

Mutations - all good except the first combo
0.0 0

#1

Hi

Can someone help me see why my code is not working for the first example?
I’ve checked other examples but can’t see the difference.

My code is a bit long but it shows my thinking process. (Still learning that nice simplified clean code :sunglasses: )

function mutation(arr) {
  

  var string1 = arr.slice(0,1).toString().toLowerCase();
  var string2 = arr.slice(1).toString().toLowerCase();
  var array1 = string1.split('');
  var array2 = string2.split('');
    
  
  for (i = 0; i < array2.length; i++) {
    var result = array1.indexOf(array2[i]);
    if (result >= 0){
      return true;
    } else {
      return false;
    }
  }

}

mutation(["hello", "hey"]);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36.

Link to the challenge:


#2

Hey ijemz,
In your code the following will be your output.

string1 = "hello"
string2 = "hey"
array1 = [‘h’,‘e’,‘l’,‘l’,‘o’]
array2 = [‘h’,‘e’,‘y’]

So the for loop will loop 3 times. The letter ‘h’ and ‘e’ will be found so true will be returned twice and then ‘y’ is not found so it will return false.

So since ‘true’ is being returned first you are getting the wrong answer.
Hope this makes sense to help you proceed.


#3

Actually, you are incorrect in part of your explanation. The for loop will only iterate one time and one time only. Why? Because in the first iteration result = 0 and since the if statement checks if result >= 0, the value true is returned to the calling function. Once a return statement is executed, the function is immediately exited and does not come back. It breaks out of the for loop.