Using the forEach() Method

I’ve been going through “The Web Developer Bootcamp” in udemy.com and this was today’s exercise.

Yesterday Cole talked about the forEach() method but it didn’t click until today.

In layman’s terms this forEach will callback the funtion buildString “You have…” and concat it with the properties from each movie.

I’m sure as I get more advanced I will see other uses for this method.

FYI You can leave comments now that I’ve fixed the disqus plugin.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
var movies = [
{
title: "Jaws",
rating: 5,
hasWatched: true,
},
{
title: "Jurassic Park",
rating: 3,
hasWatched: true,
},
{
title: "Indiana Jones: Raiders Of The Lost Arc",
rating: 4,
hasWatched: true,
},
{
title: "Star Wars: A New Hope",
rating: 2.5,
hasWatched: false,
}];
function buildString(movie){
var result = "You have ";
if(movie.hasWatched){
result += "watched ";
} else {
result += "not seen ";
}
result += "\"" + movie.title + "\" - "
result += movie.rating + " stars"
return result;
}
movies.forEach(function(movie) {
console.log(buildString(movie));
})
// Output
You have watched "Jaws" - 5 stars
You have watched "Jurassic Park" - 3 stars
You have watched "Indiana Jones: Raiders Of The Lost Arc" - 4 stars
You have not seen "Star Wars: A New Hope" - 2.5 stars