0
0
Javascriptprogramming~15 mins

Why loops are needed in Javascript - See It in Action

Choose your learning style9 modes available
Why loops are needed
📖 Scenario: Imagine you have a list of fruits and you want to say hello to each fruit one by one. Doing this without loops means writing the same message many times. Loops help us repeat actions easily.
🎯 Goal: You will create a list of fruits, set up a counter, use a loop to greet each fruit, and finally print all greetings.
📋 What You'll Learn
Create an array called fruits with these exact values: "Apple", "Banana", "Cherry"
Create a variable called greetings and set it to an empty array
Use a for loop with variable i to go through fruits
Inside the loop, add a greeting string `Hello, ${fruits[i]}!` to greetings
Print the greetings array
💡 Why This Matters
🌍 Real World
Loops are used in many apps to process lists of items, like showing messages for each user or calculating totals.
💼 Career
Understanding loops is essential for any programming job because they make code efficient and easier to maintain.
Progress0 / 4 steps
1
Create the fruits array
Create an array called fruits with these exact values: "Apple", "Banana", "Cherry"
Javascript
Need a hint?

Use square brackets [] to create an array and separate items with commas.

2
Create an empty greetings array
Create a variable called greetings and set it to an empty array []
Javascript
Need a hint?

An empty array is created with [].

3
Use a for loop to add greetings
Use a for loop with variable i to go through fruits. Inside the loop, add a greeting string `Hello, ${fruits[i]}!` to the greetings array using push()
Javascript
Need a hint?

Use fruits.length to get the number of fruits and push() to add items to the array.

4
Print the greetings array
Write console.log(greetings) to print the greetings array
Javascript
Need a hint?

Use console.log() to show the array in the console.