Need help with JS while loop

Need help with JS while loop
0.0 0

#1

When I save this file and open my browser, It doesn’t “console.log” anything at all, can someone tell me what I did wrong here?


#2
var movies = [
	{	
		title: "In Bruges",
		hasWatched: true,
		stars: 5,
	},
	{
		title: "Frozen",
		hasWatched: false,
		stars: 4.5,
	},
	{
		title: "Mad Max Fury",
		hasWatched: false,
		stars: 5,
	},
	{
		title: "Les Miserables",
		hasWatched: false,
		stars: 3.5,
	}
];

while (movies[0] <= movies.length) {
		if (movies.hasWatched != true) {
			console.log("You have not seen " + movies.title + " - " + movies.stars + " stars.")
		}
		else {
			console.log("You have watched " + movies.title + " - " + movies.stars + " stars.");
		}
	movies++;
}

#3

You don’t see the log messages because the while loop never gets into the loop—the condition that you specified is always false.

movies[0] returns the first object inside the array, and it will always return false if you compare to the length of the array. :slight_smile:


#4

You need an index to iterate over the movies array. The array is also zero-indexed so you go from 0 to length-1. Something like:

var index = 0;
while (index < movies.length) {
  var current = movies[index];
  if (current.hasWatched != true) { ... } else { ... }
  index++;
}

#5

Thanks! Now it is counting. I’m new to coding, so I’m a bit confused about it all…

var index = 0;
while (index < movies.length) {
	var current = movies[0];
		if (current.hasWatched != true) {
			console.log("You have not seen " + movies.title + " - " + movies.stars + " stars.")
		}
		else {
			console.log("You have watched " + movies.title + " - " + movies.stars + " stars.");
		}
	movies++;
}

Changed it to this, but now I get “events.js:31 You have watched undefined - undefined stars.” …
Are my selectors not working correctly or what is wrong here?


#6

replace

console.log("You have not seen " + movies.title + " - " + movies.stars + " stars.")

with

console.log("You have not seen " + current.title + " - " + current.stars + " stars.")

#7

you incremented the movies instead of the index
you could also swap the the result so you don’t have to use != operand

var i = 0;
while(i < movies.length) {
  if(movies[i].hasWatched){
    console.log('You have seen '+movies[i].title+' - '+movies[i].stars+'stars.')
  }else{
    console.log('You have not seen '+movies[i].title +' - '+movies[i].stars+'stars.')
  }
  i++;
}

PS: i got consfused, didn’t notice which answer you were following. disregard my answer…


#8

Thank you very much, guys! It works :slight_smile: