Course progress0%
Course content
30 min

From One Value to a List

Represent several resources and display them safely

By the end of this lesson

  • Represent interface data as an array of objects
  • Build DOM elements from a list without mixing in application decisions

Add only one difficulty

The first lesson displayed one string. Now the resource library needs several records. Each record describes one real concept in the application.

const resources = [
  { id: 1, title: 'Understanding HTTP', topic: 'web', minutes: 18, available: true },
  { id: 2, title: 'Working with State', topic: 'frontend', minutes: 24, available: true },
  { id: 3, title: 'Debugging Data Flow', topic: 'debugging', minutes: 20, available: false }
];

The array represents the collection. Each object represents one resource. Properties retain their useful types: minutes is a number and available is a Boolean.

Display the list

const listElement = document.querySelector('#resource-list');

for (const resource of resources) {
  const itemElement = document.createElement('li');
  itemElement.textContent = `${resource.title} - ${resource.minutes} min`;
  listElement.append(itemElement);
}

We use textContent because the resource title is data, not trusted HTML. Inserting external text with innerHTML can make the browser interpret markup that the application never intended to create.

Follow one record

resources[1]
    |
    v
loop variable: resource
    |
    v
new <li> element
    |
    v
textContent
    |
    v
visible list item

A hidden problem

Run the display loop twice. The page now contains duplicate items because each execution appends more elements. The code can create the initial interface, but it cannot yet recreate a correct interface after a change.

That problem gives us a reason to introduce render() in the next lesson.

Small practice

Add one resource object with a unique numeric id. Predict the list length before running the code. Then deliberately run the loop twice and explain the duplicate result using DOM operations.

What to remember

Arrays and objects describe application data. DOM elements present that data. A loop can build the first list, but repeatable updates need a clearer rendering rule.

Lesson complete?

Your progress is saved on this device.