sleepylog
sleepylog

Reputation: 67

'for' loop not looping through object array properly

When I run the very simple following code, for some reason I get the following result in the browser console: "6 You have not watched undefined undefined." Can anyone point out my error please?

var movies = [{
    title: "The Mummy",
    hasWatched: true,
    stars: "5 stars"
  },

  {
    title: "About A Boy",
    hasWatched: true,
    stars: "5 stars"
  },


  {
    title: "It",
    hasWatched: false,
    stars: "5 stars"
  },


  {
    title: "Cleopatra",
    hasWatched: false,
    stars: "5 stars"
  }

];

for (var i = 0; i <= movies.length; i++) {
  if (movies.hasWatched) {
    console.log("You have watched " + movies.title + " " + movies.stars + ".");
  } else {
    console.log("You have not watched " + movies.title + " " + movies.stars + ".");
  }

}

Upvotes: -1

Views: 220

Answers (3)

Vivek Venkatachari
Vivek Venkatachari

Reputation: 103

for (var i = 0; i <= movies.length; i++) {
  if (movies[i].hasWatched) {
    console.log("You have watched " + movies[i].title + " " + movies[i].stars + ".");
 } else {
    console.log("You have not watched " + movies[i].title + " " + movies[i].stars + ".");
  }

}

you were just missing the index identifier while accessing

Upvotes: 1

Omer Iqbal
Omer Iqbal

Reputation: 2293

Change the for condition to i < movies.length; you have one extra iteration. And you also need to references movies[i] to get the actual movie, for example, movies[i].title.

In the above example, the last index is 3 (items are numbered 0, 1, 2, 3), but your loop is going until 4 and will attempt to find movies[4].title and return undefined.

Upvotes: 2

j08691
j08691

Reputation: 207891

You have an array of objects so you need to reference the index of each array element. You also need to reduce your loop by one since array indexes are zero-based but the length is not.

var movies = [{
    title: "The Mummy",
    hasWatched: true,
    stars: "5 stars"
  },

  {
    title: "About A Boy",
    hasWatched: true,
    stars: "5 stars"
  },


  {
    title: "It",
    hasWatched: false,
    stars: "5 stars"
  },


  {
    title: "Cleopatra",
    hasWatched: false,
    stars: "5 stars"
  }

];

for (var i = 0; i < movies.length; i++) {
  if (movies[i].hasWatched) {
    console.log("You have watched " + movies[i].title + " " + movies[i].stars + ".");
  } else {
    console.log("You have not watched " + movies[i].title + " " + movies[i].stars + ".");
  }

}

Upvotes: 3

Related Questions