Rylan McCarty Rylan McCarty - 1 year ago 55
Javascript Question

specific bug in code when iterating using indexOf() Javascript

I have been going through the FreeCodeCamp's Bonfire algorithm challenges, and with this particular challenge we are given two parameters and asked to use indexOf() to match up all of the characters from the second parameter's string with the first one, and if the second parameter contains a letter that is not present in the first parameter the function should return false.

With the function I have written here, I pass all of the test parameters that they use except for when they pass:

mutation("hello", "hey");

Even when I try running the function in other places, calling this function with the parameters above still returns true where it should be returning false.

function mutation(arr) {

var arr0 = arr[0].toLowerCase();
var arr1 = arr[1].toLowerCase().split(''); //breaks characters into an array

for (var i = 0, length = arr1.length; i < length; i++) {

var check = arr0.indexOf(arr1[i]); // each element in arr1 is checked
if (check === -1) { // against arr0
return false;
return true;

mutation(["hello", "hey"]); //returns true, but I can't find out know why

Answer Source

Move this out of the loop:

return true;

so after the brace that follows it.

This is because you can only know whether the result is true when you have checked all the characters. As you have it now the for-loop actually never loops, it always returns on the first iteration.