2059↗learn.

Arrays & iteration

Work with a collection of values.

Keep related items together

An array is an ordered collection. Its first item has index 0. The length property tells you the number of items. Arrays can hold strings, numbers, objects, and other values.

Visit each item

forEach calls a function for each existing array item. This example creates an li for each topic. Creating elements and assigning textContent avoids interpreting the topic as HTML.

Change the data

Add another topic to the array and run the example. The rendering code stays the same because it works with the collection instead of a fixed set of elements.

Try the example

<h1>A small learning list.</h1>
<ul id="topics"></ul>
<script>
  const topics = ["Structure with HTML", "Style with CSS", "Interact with JavaScript"];
  topics.forEach((topic) => {
    const item = document.createElement("li");
    item.textContent = topic;
    document.querySelector("#topics").append(item);
  });
</script>

Enable JavaScript to edit and run the example in the playground.

Your turn

Add a fourth topic. Then show the number of topics in a new paragraph using topics.length.

Check your understanding

What is the index of the first array item?

  • 1
  • 0
  • -1
Show answer and explanation

0. JavaScript arrays use zero-based indexing.

MDN reference ↗

Next lesson →

Search by topic, concept, or language. Escape to close.

Reset local data?