Why is it not returning false?

I’m on this challenge https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/mutations

This is what I have

function mutation(arr) {
  var chars = arr[0].split("");
  var word = arr[1].split("");
  chars.forEach(c => c.toLowerCase());
  word.forEach(e => {
    if(!chars.indexOf(e.toLowerCase())) {
      return false;
    };
  })
  return true;
}

mutation(["hello", "hey"]);

Before the return false, if I put a console.log it prints, but it doesn’t return false. It fails on the first test but works on most of them. It prints the first word after the if, so it should return false, but it doesn’t. Any ideas why?

I thought indexOf returned -1 when the item wasn’t found? -1 is truthy

I didn’t know that, however I replaced it with if(chars.indexOf(e.toLowerCase()) < 0) {, it prints as well but still doesn’t return false

You can not return out of forEach.

const numbers = [1, 2, 3, 4, 5, 6];

function returnEvenForEach(numbers) {
  numbers.forEach((number) => {
    if (number % 2 === 0) {
      return 'Is even';
    }
  });
}

console.log(returnEvenForEach(numbers)); // undefined
function returnEvenForOf(numbers) {
  for (const number of numbers) {
    if (number % 2 === 0) {
      return 'Is even';
    }
  }
}

console.log(returnEvenForOf(numbers)); // Is even
2 Likes

Beat me to it.

Basically, you pass a function of e to the forEach for it to run on each element. When you return inside of that function, you are just returning to the forEach.

Edit: you could get similar logic if JS has a find or findFirst method.