FAQ: Code Challenges: Intermediate JavaScript - isTheDinnerVegan()

A couple of things could be happening since I can’t see your full code.

  1. Make sure you’re passing in an array into the isTheDinnerVegan function; you need to pass an array in for this to work.
  2. Inside that array, you should have objects. Those objects should have source as instance variables.
  3. You want to call plantSource on each of those objects. Hint: make use of the i variable you have in your for loop declaration.
1 Like

// Alternate solution:
// Using a function declaration, loop, and helper function:
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
}

Hello everyone, this is the alternate solution given by codecademy. Can anyone explain to me why is there an additional ‘return true’ statement outside the for loop? Thanks!

Welcome to the forums! You can format code using the </> button for better readability and to preserve indentation.

Once a return statement is executed, you immediately exit the function. This means that no more code inside the function will run for that particular function call. Therefore, if one of the food items had a source that was not 'plant', return false would execute and the function would be exited. However, if all of the food items had 'plant' as their sources, then we’d complete all the iterations of the for loop without returning anything. In this case, since we know that all of the food sources are 'plant' we can return true.

Example

function isEven(array) {
    for (let i = 0; i < array.length; i++) {
        if (array[i] % 2 != 0) {
            return false;
        }
    }
    return true;
}

In the above example, we made a function where we want to return true if all the numbers in an array are even and false otherwise. If at any point we encounter an odd number, return false will execute and the function will be exited. However, if all the numbers are even, we will finish going through the for loop without returning anything. Because we haven’t returned anything and the function is still executing, we can return true because we know that all the numbers in the array are even.

1 Like

Thank you so much for your explanation!! It is very clear! I understand now :grinning:

(And oops thanks for telling me about the </> button XD first time using the forum so I don’t know the functions very well :sweat_smile:)

1 Like

Thanks victoria!

Here’s what worked, legend

function isTheDinnerVegan (array) {
for (let i = 0; i < array.length; i++) {
return plantSource(array[i])
}
}

Edit: For God’s sake… nope didn’t work, because the ‘return’ doesn’t let the loop work on every element, so the result I was getting was only in reference to the first element.

I am at a complete loss here, all I keep getting is undefined.

I also tried

‘plantSource(i)’

in the above code and still getting undefined…

How do I do this without a return statement?!

This won’t work. i is an integer, not an object from which you can determine whether it is vegan.


Please post all of your code (everything) and format it according to the topic below so that we can get a better sense of what is going on.

1 Like

Thanks Vic

Here’s the code in it’s entirety:


  if (food.source === 'plant'){

    return true;

}

      return false;

}


function isTheDinnerVegan (array) {
   for (let i = 0; i < array.length; i++) {
     return plantSource(array[i].source)
}
}

Running the code with this: return plantSource(array[i].source)

gives a true or false result, but wrongly so (as in the answer is not accurate).

Is this all of your code? If so, the plantSource function doesn’t exist. You need to create this function and put your if and return statements inside it.

Also, take a look at a previous reply I made in this topic that explains how return works and why you shouldn’t be using it in your specific case inside the for loop.

I love the conciseness of arrow function

const isTheDinnerVegan = array => array.every(elem => elem.source === 'plant');

Oops, I made a mistake, I left out the actual function.


 const plantSource = (food) => {
if (food.source === 'plant'){
  return true;
}
 return false;
}


function isTheDinnerVegan (array) {
   for (let i = 0; i < array.length; i++) {
   plantSource(array[i].source)
}
}

I really don’t know what to do with this now, there have been a couple of Codecademy problems where i just haven’t been able to solve them, and it leaves a real sense of frustration and incompleteness.

a) In terms of the ‘i’, I’m not sure how else to use it with the plantSource function. Is there any article you recommend which could directly lead me to the solution for this?

b) When I remove the ‘return’, all I get is an undefined result. If I use console.log, I just get a print out of true/false for each element, rather than one true or false result.

Note: I solved this using the .every function, but until I solve it ‘manually’, I don’t think I’ll ever be a decent programmer worth my salt.

In the above code, you are using i correctly (as in you are using it to index into array). Rather than point you to an article, I think it would be more beneficial to review the lessons on for loops, arrays, and array indices.

All functions must return something. When there is no explicit return statement in the function, the default value of undefined is returned.


I think what could be very useful is to take a step back and reevaluate what you are trying to accomplish. Let’s look at the big picture. What is the one overall thing you are trying to accomplish with this entire program? Now, take that goal and divide it into smaller, more manageable goals that you can accomplish. Now divide those goals again until you’re left with the simplest goals you need to achieve in order to complete this exercise. What steps do you need to take to achieve those simple goals?

Based on your above code, two questions I think could help guide you toward getting this to work are: 1) How can you figure out whether a certain meal is vegan or not? and 2) Based on the result from question 1, what do you want to do if a certain meal is not vegan?


It’s great that you found an alternate solution using .every(). I encourage you to solve it using this more naive approach; I believe you’ve just overthought the problem, so try answering the questions I put above and see if that helps. Even if it takes several attempts and posts on the forums, keep working on it until you solve it!

1 Like

Finally solved it! Here is the updated code for the loop part:

function isTheDinnerVegan(array){
 

for (let i = 0; i < array.length; i++) {
    if (!plantSource(array[i])) {
      return false
    } 
}
return true

} 

So basically, if not every element of the array.source is ‘plant’, it will return false!

Looks great! Happy coding! :slight_smile:

I don’t understand this solution. Where does “food.source” come from in this function? Shouldn’t it be “dinner.source” since “dinner” the name of the variable and we are then referring to the “source” property?

const isTheDinnerVegan const isTheDinnerVegan = arr => arr.every(food => food.source === ‘plant’);

const dinner = [{name: ‘hamburger’, source: ‘meat’}, {name: ‘cheese’, source: ‘dairy’}, {name: ‘ketchup’, source:‘plant’}, {name: ‘bun’, source: ‘plant’}, {name: ‘dessert twinkies’, source:‘unknown’}];

console.log(isTheDinnerVegan(dinner))

So I tried using this function:

function isTheDinnerVegan(foods) {
return foods.every( item => item.source === 'plant');
}

with this test array:

const dinner = [{name: 'spinach', source: 'plant'}]

and it returns TRUE. However if I add curly brackets after the arrow:

function isTheDinnerVegan(foods) {
return foods.every( item => {item.source === 'plant'});
}

it returns FALSE. Why does adding the curly brackets flip the Boolean the way that it does? Any help is appreciated, thanks!

You aren’t returning the function at the right spot, depending on the function formula you use, you must return it in the proper spot.

I like using this function formula

function isTheDinnerVegan(obj){
  return obj.every(item=> item.source === 'plant')
}

If I had omitted the return there, my function would have also been undefined. If you look in the documentation they mention some methods return as undefined on their own but if you return everything then it works. They mentioned that in passing in a lesson but it should have been a lesson on its own

don’t get frustrated, tbh these courses aren’t the best way to learn a lot of the things. it just requires more practice, Its the 3rd time I have taken this course and its the first time I can solve them without looking at the hints.

you feel like you are cruising but in reality you are learning to copy and paste, it will take repetition for you to learn this stuff

because in your code, you aren’t checking for EVERY item in the dict.

I used the built in method every to solve for this in one line

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

Can someone tell me why I keep getting this error message on the console? Thanks! (Sorry for bad English)

" if(!(arr[i].source === 'plant')) {
                 ^
TypeError: Cannot read property 'source' of undefined
    at isTheDinnerVegan "

Your function expects an array which contains multiple objects as an argument. These objects should contain a key named ‘source’. But that doesn’t seem what it receives: arr[i] is undefined. What do you pass as an argument?