Intermediate JavaScript, isTheDinnerVegan – alternative solution

I do not understand the alternate solution:

function isTheDinnerVegan(arr) {
      const isVegan = (food) => {
            if (food.source === 'plant') {
                  return true;
            return false;
      for(let i = 0; i<arr.length; i++){
            if (!isVegan(arr[i])){
                  return false 
      return true

Anyone able to explain where things stop? I don’t see what happens here step by step.

Thank you so much!

Ok this function isTheDinnerVegan works as follows:

The function has one input parameter arr which is an array of objects, each object representing a meal and their ingredient like so

{name: 'arugula', source: 'plant'} 

Upon calling you have to pass any meal. It will return a boolean which states if the dinner is Vegan or not (true or false). So far so good. That is exactly what we want.

The first part of the function is de definition of another function isVegan which is later called during the second part.

What isVegan does is check the food.source key which is stored in the object. If the food source equals 'plant', thus vegetarian, it will return a boolean value of true. If not it will return a false.

Now for the second part of the function:

This part consists of a for loop that iterates past each meal (object) inside the array. For each meal it calls the earlier defined function isVegan with the meal as input (arr[i]).

However what it does is it uses an if statement which might be a bit confusing. isVegan returns a true when a meal is vegetarian and a false when it is not.

But the if statement actually wants to know is if the meal is not vegan. It does this by turning a false from isVegan into a true using a !, so that the moment the if statment checks a meal which is not vegan, it will stop doing what it does and return a false as output of the isTheDinnerVegan function. If it encounters only plant based meals it will pass through the for loop uninterrupted and return a true.

Does this clarify to you how isTheDinnerVegan works?


So in case of a hamburger the isVegan function would return a false and then, thanks to the exclamation mark of the !isVegan condition, the code within this condition would run and the isTheDinnerVegan function would result in a false. right?

thanks so much!

1 Like

Yep you got it ;). No problem.

1 Like