FAQ: Code Challenges: Intermediate JavaScript - isTheDinnerVegan()

Type Coercion : With == , JavaScript will attempt to convert the operands to the same type before making the comparison. This can lead to surprising results. For example:

1 == '1'; // true, because '1' is converted to a number
0 == '';  // true, because '' is converted to 0

Strict Comparison : === does not perform type coercion. It simply compares both the value and the type. For example:

1 === '1'; // false, because the types are different
0 === '';  // false, because the types are different

Hi,
I put in the following code and was expecting that the moment the callback function encounters a non-plant source it would return false. But strangely, it didn’t! Can someone why the function didn’t return false. Thanks.

const isTheDinnerVegan = (arr) => {
let source;
arr.forEach(item => {
if(item.source != ‘plant’) { return false;
} else source = ‘plant’;
});
if(source == ‘plant’) return true;
}

Regards
Prabir

What is the first important detail we learn about, Array.forEach()?

Thanks. Read the Docs. forEach() will loop through ALL elements & " There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool."

1 Like

That is one aspect of its behavior, and important to know, but not ‘the first rule’ as I recall. It is that Array.forEach() does not have a return, and we cannot force one upon it. The return from it will always be, ‘undefined’.

We might also respect the callback as a pure function with no contact from/to the outside. We can bind it to an outside object by specifying a thisArg but now we are not a pure function. Still, it’s a usable code model. .forEach() is permitted to have side effects so long as we closely watch them.

Let’s start from scratch by you telling us what we are expecting from the function, and what are its accepted arguments? We’d rather do this than just rewrite your code. The object is to help you rewrite it. Fair?

1 Like