Hey there, coder!
Welcome to our tutorial on For Loops in JavaScript! By the end of this tutorial, you'll be able to use For Loops to iterate over arrays and perform tasks on each item. Let's get started!
Task: Display each item in a list of products
Step 1: Create a sample array of products
Open your index.js
file and add the following code:
const products = [ "Apple Watch", "Samsung TV", "Nike Shoes", "Sony Headphones", "Levi's Jeans",]
This array contains a list of products that we'll iterate over using a For Loop.
Step 2: Write a For Loop to iterate over the products array
Add the following code below the products
array:
for (let i = 0; i < products.length; i++) { // We'll add code here to display each product}
Here, we're using a For Loop to iterate over the products
array. The loop will run as long as i
is less than the length of the products
array.
Step 3: Display each product using Template Literals
Inside the For Loop, add the following code:
for (let i = 0; i < products.length; i++) { console.log(`Product ${i + 1}: ${products[i]}`)}
We're using Template Literals to display each product in the console. The ${i + 1}
part will display the product number (starting from 1), and ${products[i]}
will display the product name.
Step 4: Run the code!
Click the "Run" button to execute the code. You should see the following output in the console:
Product 1: Apple WatchProduct 2: Samsung TVProduct 3: Nike ShoesProduct 4: Sony HeadphonesProduct 5: Levi's Jeans
Congratulations! You've successfully used a For Loop to iterate over an array and display each item.
Real-world example: Imagine you're building an e-commerce website, and you need to display a list of products on the homepage. You can use a For Loop to iterate over the products array and generate HTML elements for each product.
That's it for this tutorial! You've learned how to use a For Loop to iterate over an array and perform tasks on each item.
Next steps:
name
, price
, and description
.Keep coding, and we'll see you in the next tutorial!
Tests