Objects inside Array in Javascript

I have an Array,

var moviesArray = [{
		title : "In Bruges",
		rating : 5,
		hasWatched : true
	},{
		title : "Frozen",
		rating : 4.5,
		hasWatched : false

	},{
		title : "Mad Max Fury Road",
		rating : 5,
		hasWatched : true
	},{
		title : "Les Miserables",
		rating : 3.5,
		hasWatched : false
	}
]

I have to show something based on this array. Like,

11

My code so far:

//for title - moviesArray[i].title
//for rating - moviesArray[i].rating
//for hasWatched - moviesArray[i].hasWatched

for(i = 0; i < 4; i++){
	if(moviesArray[i].hasWatched === true){
		console.log("You have watched " + '"' + moviesArray[i].title + '"' + " - " + moviesArray[i].rating + " stars");
	}else{
		console.log("You have not seen " + '"' + moviesArray[i].title + '"' + " - " + moviesArray[i].rating + " stars");
	}
}

Is that an efficient way to fix this? Do you have any better idea?

I would avoid using fixed numbers, this is prone to errors.

Also there are way to “shorten” the syntax so you’d type less, but that doesn’t necessary means achieving better performances, so it’s more an “aesthetic” preference.

For example I am lazy, so I don’t like to type all those string concatenation thus I prefer Template strings.
Also typing all that for conditions is boring, a forEach will do as well.

Finally I try to not repeat myself, so I would try a way to avoid typing those variables more than once, if possible.

moviesArray.forEach(movie => {
  const {title, rating, hasWatched} = movie;
  const s = hasWatched 
    ? `You have watched ${title} - ${rating} stars`
    : `You have not seen ${title} - ${rating} stars`;

  console.log(s)
});

Again this is mainly aesthetic preference: nothing “better” per-se in this code compared to what you have :slight_smile:

1 Like