I am writing a function in Javascript. Basically, it should return true 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. I am testing my function on the input ["hello","hey"]
function mutation(arr) { var string1 = arr[0].toLowerCase(); var array=[]; for (i=0;i<=string1.length-1;i++) { array[i]=string1[i]; } var string2 = arr[1].toLowerCase(); var result = true; label: for(i=0;i<string2.length;i++) { if (array.indexOf(string2[i]) == -1) { result = false; break label; } else { result = true; } } return result; } This would give me the correct result false. However, if I write my loop in a different way, then it would give me true.
label: for(i=0;i<string2.length;i++) { if (array.indexOf(string2[i]) == -1) { return false; break label; } else { return true; } } Where did I do wrong in my second method?
33 Answers
A return statement terminates the function immediately. In the second implementation early returning false is indeed correct, but the return true statement is wrong - it will return true on the first element isn't contained in the second array. Effectively, you're negating the loop - only the first element is examined, and a value returned immediately.
What you intended here is to early-return only false values:
for (i = 0; i < string2.length; i++) { if (array.indexOf(string2[i]) == -1) { return false; } } // If we finished the loop and haven't returned false, the return value is true: return true; 1Your second method breaks at this point:
return true
The moment the return occurs in a positive match, your FOR loop terminates.
In your initial version, because it is only setting the result = true, the FOR loop continues, until it encounters a FALSE, then your explicit BREAK occurs.
However, in the other version, the if statement will encounter either a RETURN FALSE or a RETURN TRUE, it will iterate only once, returning a result and ending the FOR loop.
In your first case, the logic was quitted and returned the value false, as long as it satisfied the condition (array.indexOf(string2[i]) == -1) in your case.
In the second case, the first element of your array didn't satisfy the condition and fell into the else condition, thus quitted with true returned.