Mutations help - Basic Algorithm script using forEach() method

First, I know there are other ways to solve this problem that pass the test. I personally like to pass the test multiple ways to see how various tactics can solve the same problem. With that said the code below seems to solve the problem (the logging shows the correct logic), but for some reason it doesn’t pass the test. Am I missing something with my code or is this a bug with the FreeCodeCamp test? :thinking:

   **Your code so far**

function mutation(arr) {
 const A = arr[0]
 const B = arr[1].split('')
 
 console.log(`A = '${A}'
B = [${B}]`)
 
 B.forEach(el => {
   console.log(`Is ${el} absent from ${A}?
 • ${!A.includes(el) ? 'Correct' : 'Incorrect'}`);
   if (!A.includes(el)) {
     console.log(`"${A}" does not contain "${el}" which makes the whole thing "false".`);
     return false
   }
 });
return true;
}

mutation(["hello", "hey"]);
   **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1 Safari/605.1.15

Challenge: Mutations

Link to the challenge:

I just realized my error. It is that there is no way to stop or break a forEach() loop other than by throwing an exception. So I cannot “return” false directly from within the forEach method. In order to get a working solution using forEach() I needed to use a variable that I call ‘answer’ and set it to false inside the forEach() method if the current element of the array is not present.

I get that this is not the best overall solution. It was a personal challenge to get this working with forEach(). I tried the same with the every() method and it works as well. This was a great learning experience.

See the following solution:

function mutation(arr) {
const A = arr[0].toLowerCase()
const B = arr[1].toLowerCase().split(’’)
let answer

console.log(A = '${A}' B = [${B}])

B.forEach(el => {
console.log(Is ${el} absent from ${A}? • ${!A.includes(el) ? 'Correct' : 'Incorrect'});
if (!A.includes(el)) {
console.log("${A}" does not contain "${el}" which makes the whole thing "false".);
answer = false
}
});
if (answer != false) {
console.log(‘Return true.’)
return true;
} else {
console.log(‘Returns false.’)
return false;
}
}

mutation([“hello”, “hey”]);

1 Like

Just because forEach() can work doesn’t mean it should be used in real world use cases similar to this code challenge. That is because the forEach() method runs through each item in the array. Meaning that even if the first element fails the test the method will continue until the end. Unnecessary processing = less than optimal performance.

The every() method can be exited before processing all the items in the array, so it is a more practical real world solution.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.