Mutations - not sure why code doesn't work

Hi,

I have solved this algorithm, but I can’t figure out why what I initially tried didn’t work. I might be missing something really obvious, because it seems to me like it should.

I was hoping someone could explain this to me just so I know for the future?

Here’s what I originally tried (I also tried > 0 instead of >= 1):

function mutation(arr) {
  var test = arr.pop().toLowerCase();
  var target = arr.pop().toLowerCase();
  var x = 0;
  var result = ""; 

  while (x < test.length) {
    if (target.indexOf(test.charAt(x)) >= 1) {
      result = true;
     }
    else {
    return false;
    }
  x++;
  } 

  return result;
}
mutation(["floor", "for"]);

And here’s what I ended up with, that actually worked:

Your code so far

function mutation(arr) {
  var test = arr.pop().toLowerCase();
  var target = arr.pop().toLowerCase();
  var x = 0;
  var result = ""; 
 
  
  while (x < test.length) {
    if (target.indexOf(test.charAt(x)) == -1) {
      return false;
      }
    else {
      result = true;
    }
    x++;
      
  }

  return result;
}
mutation(["floor", "for"]);

I don’t understand why flipping around the if statement got it working.

Thank you. :slight_smile:

Your browser information:

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

Link to the challenge:
https://www.freecodecamp.org/challenges/mutations

First of all I will link you the MDN docs related to the method ‘indexOf’ ( MDN Docs - String.prototype.indexOf); this is the point to look at:

Returns -1 if the value is not found

It means that in your first code you should have written >=0 or > -1, otherwise you would have missed the case when the first char match.
If you change that it will works :slight_smile:

That does work. Thank you! :slight_smile:
I keep forgetting about counting starting at 0.

1 Like