SheTech
  • SheTech JS bootcamp
  • Level 1 - awesome tasks
    • Introduction to Awesome Tasks
    • Step 1: HTML
    • Step 2: playing with the DOM
    • Step 3: add a new task
    • Step 4: dynamic list of tasks
    • Step 5: adding new items
    • Step 6: removing items
    • Step 7: add some style
    • Step 8: marking items as done
    • Step 9: saving items in the localstorage
    • Step 10: adding filters and bulk actions
    • Step 11: add counters
    • From Awesome Task to the next big thing!
  • Level 2 - timeline
    • Live Timeline
    • Step 1: basic HTML page
    • Step 2: add util library
    • Step 3: show all posts
    • Step 4: add form
    • Step 5: collect form data
    • Step 6: create a new post
    • Step 7: validating posts
    • Step 8: refactoring
    • Step 9: refresh button
    • Step 10: auto refresh
  • Code Editors
  • Useful resources
  • API Reference
  • Glossary
Powered by GitBook
On this page
  • What this code do?
  • How to use forEach

Was this helpful?

  1. Level 2 - timeline

Step 3: show all posts

PreviousStep 2: add util libraryNextStep 4: add form

Last updated 4 years ago

Was this helpful?

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 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.

forEach