Mutations Algorithm Solution Question

Mutations Algorithm Solution Question
0

#1

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?


#2

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


#3

Ohh, thank you very much!


#4

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.


#5

Makes sense, thank you :slight_smile: