Step 3: show all posts

Replace the content of the last then callback to print out all the items we have. We do this with the the help of the forEach function

toArray(posts).forEach(function(postToAdd) {
  drawElement(postToAdd);
});

What this code do?

Now we use the array returned by the toArray(posts) invocation to draw all the items of the list.

forEach

forEach is a method that can be called on an array and that executes the provided function once for each element of the array.

Parameters of the provided function are:

  • The current element value that is processed in the array.

  • The current element index of the array.

  • The array that forEach() is being applied to.

How to use forEach

For example, We want to log the content of this array with forEach:

var arr = ['a', 'b', 'c', 'd'];

We can write:

arr.forEach(function(value, index) {
    console.log(index, value);
});

//Will log:
//  0 "a"
//  1 "b"
//  2 "c"

What we just did:

  • We used toArray(posts) function to transform the posts variable from an object into an array.

  • We used forEach to print each items of the posts list instead of only one.

Last updated