lundi 22 août 2016

How does using curly braces in if-statements within for-loops affect code?

This is an algorithm that Returns true, ONLY IF the string in the first element of the array contains all of the letters of the string in the second element of the array:

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

mutation(["hello", "hey"]) returns false

mutation(["Mary", "Aarmy"]) returns true.

mutation(["voodoo", "no"]) returns false.

mutation(["hello", "neo"]) returns false

HOWEVER, if I put curly braces around the "if" statement:

for (i=0;i<test.length;i++) {
  if (target.indexOf(test[i]) < 0) {
  return false;
  }
return true;
}

mutation(["hello", "hey"]) returns TRUE.

mutation(["Mary", "Aarmy"]) returns true.

mutation(["voodoo", "no"]) returns false.

mutation(["hello", "neo"]) returns false

I was always taught to use curly braces in if-statements, and looking at similar questions, it seems curly braces (with or without) make no difference.

So I'm confused why only "mutation(["hello", "hey"])" is changed.

Aucun commentaire:

Enregistrer un commentaire