Skip to main content

Exercise 24: Counting the Length of Each Word with forEach()

Use forEach() in JavaScript to iterate through an array of words and count the length of each one. This reinforces your understanding of array manipulation and callback functions. The primary goal is to learn how to use it.forEach()to iterate through an array and perform operations on each element, in this case, counting the number of characters in each word.

Activity

  1. Create an array containing several words (for example, ["apple", "pear", "banana", "grape"]).

  2. UseforEach()to iterate through each word in the array.

  3. In each iteration, count the number of letters in the current word and display the result in the console.

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>Contar la Longitud de Cada Palabra con ForEach()</title>
</head>
<body>
<h1>Ejercicio 24: Contar la Longitud de Cada Palabra con ForEach()</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
const palabras = ["manzana", "pera", "plátano", "uva"];

palabras.forEach((palabra) => {
console.log(`La palabra "${palabra}" tiene ${palabra.length} letras.`);
});
info

🔎Check the sectionControl instructions in JavaScriptwhere you will find more information on this topic.