Algorithm Challenge: Mutations (Spoiler!)

Algorithm Challenge: Mutations (Spoiler!)
0

#1

So, I think I’ve got this. But I’m confused about why one of these passes and why the other doesn’t…

This does not pass.
function mutation(arr) {
  for (var i = 0; i < arr[1].length; i++) {
    if (arr[0].toLowerCase().indexOf(arr[1][i].toLowerCase()) < 0) {
      return false;
    } else {
      return true;
    }
  }
}
But this does.
function mutation(arr) {
  for (var i = 0; i < arr[1].length; i++) {
    if (arr[0].toLowerCase().indexOf(arr[1][i].toLowerCase()) < 0)
      return false;
  }
  return true;
}

Why is this? I thought best practice was to include curly braces after your if statements.


#2

In the first case the only one iteration of the for loop is executed - note that if the condition in if statement is met function returns false - if not it returns true. Either way the function returns.

In the second case for loop may is executed until the if condition is met or until ‘i’ is >= arr[1].length.
Presumably more then one time.

Kind regards,
Jarosław Pawlak