Skip to main content

Exercise 27: To-Do List with localStorage

Create a functional to-do list in JavaScript that saves the information to localStorage, even after closing the browser. The main goal is to learn how to store and manage a to-do list in JavaScript.localStoragePractice usingJSON.stringify and JSON.parseto store and retrieve arrays of objects.

Activity

  1. Create a functionagregarTarea(tarea)that receives a task (as a string) and adds the task to a task list inlocalStorage.

  2. If the task list already exists inlocalStorageAdd the new task to the existing array. If it doesn't exist, create a new array with the first task.

  3. Save the updated task list inlocalStorage4. Create a functionmostrarTareas()that retrieves the to-do list fromlocalStorageand display each task in the console.

  4. Call both functions to add and display some tasks.

Solution

Step 1: Create the index.html file

HTML
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Lista de Tareas con localStorage</title>
</head>
<body>
<h1>Ejercicio 27: Lista de Tareas con localStorage</h1>
<p>Los cambios se muestran en consola.</p>
<script src="script.js"></script>
</body>
</html>

Step 2: Write the code in script.js

JavaScript
// Función para agregar tareas al localStorage
function agregarTarea(tarea) {
// Paso 1: Verificar si ya existe una lista de tareas
let tareas = JSON.parse(localStorage.getItem("tareas")) || [];

// Paso 2: Agregar la nueva tarea al array de tareas
tareas.push(tarea);

// Paso 3: Guardar la lista actualizada en localStorage
localStorage.setItem("tareas", JSON.stringify(tareas));
}

// Función para mostrar las tareas guardadas en localStorage
function mostrarTareas() {
// Paso 4: Recuperar la lista de tareas desde localStorage
const tareas = JSON.parse(localStorage.getItem("tareas")) || [];

// Paso 5: Mostrar cada tarea en la consola
console.log("Lista de tareas:");
tareas.forEach((tarea, index) => {
console.log(`${index + 1}. ${tarea}`);
});
}

// Llamadas de ejemplo
agregarTarea("Aprender JavaScript");
agregarTarea("Practicar HTML y CSS");
agregarTarea("Estudiar localStorage");

mostrarTareas();
info

🔎Review the following sections where you will find more information on this topic:

Local Storage in JavaScript

Control instructions in JavaScript

Array methods in JavaScript