All right. 1
So here comes the answer for challenge 13. 2
We don't need to change anything inside our app.js because we're already passing over this posts 3
array to be dealt with inside our home. 4
ejs. 5
So this is where we're going to create our FOR loop and log 6
each of the titles inside our posts array. 7
Whenever you're writing code inside an EJS file 8
I recommend to start writing the Javascript code without these little scriptlet tags because they make 9
everything look a lot more cluttered and 10
it's difficult to see what's going on when you're just trying to write your code. 11
The basic FOR loop looks something like this. 12
We start off with a var called i that starts at zero 13
and it increases by one until the upper bound that we define. 14
Then we can use that i to tap into each element inside our array. 15
So let's write our FOR loop here. 16
We'll write 17
for var i = 0 18
so this is our starting point, i is less than the upper bound and the upper bound 19
in our case is the length of this post array. 20
So the number of items are currently inside our posts array 21
so we'll say posts.length. And the final thing will be i++ so that we increase by 1 each 22
time. Inside our FOR loop, we're simply going to console log the titles of each of our posts. 23
So all we need to do is console.log 24
and the thing we're going to log is posts at index i. 25
So this is how we tap into each element inside posts. 26
We use the square brackets and we tell it which one we want to access. 27
So i will start off being 0 and we'll grab the first item in our posts array and then i will increase 28
until it gets to our upper bound which is the total number of posts inside the array. 29
Posts at index 30
i.title because remember the posts array contains post object and each object has a key of title 31
and content that contains each of the post titles and bodies. Inside here 32
this is the code that we need. 33
And so now we're ready to cap everything off and go ahead and add all EJS scriptlet tags. 34
And remember that each of these tags have to be added on every single line 35
so even on the closing curly braces and any semicolons you've got. So let's hit save and let's try it 36
out. 37
So let's head over to compose and let's add a title 38
Day 1. And now let's head back to compose again 39
and let's add 40
Day 2. 41
And now we're on the home page so this is where our console.log is. 42
And now you can see we're logging Day 1 then Day 2 both the titles without the rest of the array 43
because we're looping through it and tapping into that title each time. If you need a refresher on FOR loops, 44
then this might be a good time to have a look back in the course when 45
we first introduced it or just to check out the MDN docs on FOR loops and to read up on that document 46
to remind us of how they work.