Mutations Algorithm Solution Question

Hi, I’ve just completed the Mutations challenge in Basic Algorithms. I have a quick question.

Why does this solution work:

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

and this one doesn’t?

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

The only difference is I’m putting “return true” inside an if else statement. The test that doesn’t pass is “mutation([“hello”, “hey”]) should return false.”

Why is this? Aren’t the two codes essentially the same thing?

The first time a function hits return it’s going to quit. So in the code that does not work the loop is only going to go through one time. Putting the return outside of the loop let’s the loop go all the way through it’s iteration

1 Like

Ohh, thank you very much!

A return statement ends the function execution.

The upper solution returns false as soon as it finds a condition that would be false but returns true only if all options are tested and none are found to be false.

The lower solution returns either true or false after testing the first item.

1 Like

Makes sense, thank you :slight_smile: