Let's Explore Array Functions - forEach
Hey there, coder! In this tutorial, we're going to explore another powerful feature of arrays in JavaScript - forEach
. You've already learned about arrays, loops, and functions, so this will be a breeze!
The Task: Print each task in a to-do list
Imagine you have a to-do list with several tasks, and you want to print each task to the console. We'll use an array to store the tasks and forEach
to iterate over the array and print each task.
Step 1: Create an array of tasks
Open your index.js
file and add the following code:
const tasks = ["Buy milk", "Walk the dog", "Do laundry", "Study for exam"]
Run the code to ensure everything is set up correctly. You won't see any output yet, but that's okay!
Step 2: Use forEach
to iterate over the tasks
Add the following code to your index.js
file:
tasks.forEach((task) => { console.log(task)})
Run the code to see the magic happen!
You should see each task printed to the console, one by one:
Buy milkWalk the dogDo laundryStudy for exam
What's happening behind the scenes?
When you call forEach
on an array, it executes a provided function (in this case, console.log(task)
) for each element in the array. The function is called once for each element, and the element is passed as an argument to the function.
In our example, forEach
iterates over the tasks
array, and for each task, it executes the function console.log(task)
, printing each task to the console.
Real-world example
Imagine you're building a to-do list app, and you want to display each task in a list. You can use forEach
to iterate over the tasks and generate HTML elements for each task.
Recap
In this tutorial, you learned about the forEach
method, which allows you to iterate over an array and execute a function for each element. You used forEach
to print each task in a to-do list to the console.
Next Up: Array Functions - map
In the next tutorial, we'll explore another powerful array function - map
. You'll learn how to transform an array by applying a function to each element.
For now, take a break and celebrate your progress! You're one step closer to becoming a JavaScript master!
Tests