What's wrong the code?

What's wrong the code?
0

#1

Tell us what’s happening:

Your code so far

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

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

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36.

Link to the challenge:


#2

The problem is your current logic will always return true unless the first letter of narr is different than the first letter of farr. The problem in your logic is that you return true within the first iteration of the for loop if narr’s current letter is found in farr. As soon as you use return, the function is exited and does not come back even though the for loop has not completed iterating through all the letters of narr.

The easiest way to fix your code is to return false if a letter in narr is NOT found in farr. You can safely exit the function and not worry about iterating anything else, because you found at least one letter that was not present in farr. Then, after you have iterated through the entire narr word, you can simply return true, because you know all the letters of narr exist somewhere in farr.


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

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

but this code cannot work too.~~


#4

OH~ i see~~i find out my mistake. Thanks you~


#5

I am glad you got it figured out. When you write out what needs to happen (algorithm/steps) using language, then all you have to do is find the coding syntax to implement your algorithm.

FYI - I’ve edited your post for readability. When you enter a code block into the forum, remember to 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.


#6

I See~~ Thanks very much~~