1

can someone explain why I am getting undefined in my loop? I am trying to run a loop that lets me know if its true if i've watched something as well as the rating. What am I doing wrong?

var films = [ { movie: "fast and the furious", rating: 4, seen: true }, { movie:"13 reasons why", rating: 5, seen: true }, { movie:"beaty and the beast", rating: 4, seen: false } ]; films.forEach(function(movie){ var result = "You have "; if(movie.seen) { result += "watched "; } else{ result += "not seen "; } result += "\"" + films.movie + "\" - "; result += films.rating + " stars"; console.log(result); }); 
2
  • 1
    Should be movie.movie and movie.rating. Commented May 17, 2017 at 5:22
  • you're selecting each item as movie inside forEach, if you want to access an item's properties, you'll use movie not films Commented May 17, 2017 at 5:25

3 Answers 3

1

You should access the element, not the array, in your iterator function:

films.forEach(function(movie) { var result = "You have "; if (movie.seen) { result += "watched "; } else { result += "not seen "; } result += "\"" + movie.movie + "\" - "; result += movie.rating + " stars"; }); 
Sign up to request clarification or add additional context in comments.

Comments

0

You passing a movie parameter in your function. you should use this for result.

var films = [ { movie: "fast and the furious", rating: 4, seen: true }, { movie:"13 reasons why", rating: 5, seen: true }, { movie:"beaty and the beast", rating: 4, seen: false } ]; films.forEach(function(movie){ var result = "You have "; if(movie.seen==true) { result += "watched "; }else{ result += "not seen "; } result += "\"" + movie.movie + "\" - "; result += movie.rating + " stars"; console.log(result); });

Comments

0

var films = [ { movie: "fast and the furious", rating: 4, seen: true }, { movie:"13 reasons why", rating: 5, seen: true }, { movie:"beaty and the beast", rating: 4, seen: false } ]; films.forEach(function(film){ var result = "You have "; if(film.seen) { result += "watched "; } else{ result += "not seen "; } result += "\"" + film.movie + "\" - "; result += film.rating + " stars"; console.log(result); });

Use some other variable to enter foreach and use same variable to read properties.

2 Comments

Hey so all you did was change the name of my foreach function parameter from movie to film and thats it did you edit any other code? So I kept getting an undefined method because I also have an object with movie in it right? Just trying to get a better understanding .
Actually there was 2 problem .. first is the movie object passed .. and second ... YOu are reading moviename and starts from the array itself movies.stars which is invalid .. you either need movies[key].stars or forEach object with movie.star

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.