Showing an Array

Real apps usually keep their data in an array, and the page shows what's in the array. It's the same idea as the counter: the number lived in a variable, and the page only showed it. Here, the items live in an array, and a function draws them on the page:

const fruits = ["Apple", "Pear"];
const fruitList = document.querySelector("#fruits");

function showFruits() {
    fruitList.textContent = "";
    for (const fruit of fruits) {
        const item = document.createElement("li");
        item.textContent = fruit;
        fruitList.append(item);
    }
}

showFruits();

The function first clears the list: setting textContent to an empty text removes everything inside the element. Then the loop creates one li for each element of the array. Whenever the array changes, call the function again to draw the list anew:

fruits.push("Banana");
showFruits();

Why clear the list first? Without it, each call would add all the items again, below the ones already there, and the page would show Apple, Pear, Apple, Pear, Banana.

And why the array, when you could append items straight to the page? Because then the data stays in your program, where you can work with it: count the items with .length, check for an item with .includes() or add up prices in a loop. The array can also hold objects; the text of each item is then made from their properties, for example `${product.name}: ${product.price}`.

Instructions

Write a function showTasks() that clears taskList and then, for each task in the array tasks, creates an li with the task's text and appends it to taskList. Call the function at the end of the script, so that the tasks appear when the page loads.

When addButton is clicked, add the text from taskInput to the array tasks with push(), and call showTasks() to draw the list again.

Two improvements for the handler: if taskInput is empty (its value is ""), don't add anything. And after adding a task, empty the field with taskInput.value = "";, so that the user can type the next one right away.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

9/10