Mark As Completed Discussion

Introduction to Loops

Loops are an essential part of programming as they allow us to repeat a block of code multiple times. They are used when we need to perform a task repeatedly until a certain condition is met. Loops are particularly useful when dealing with collections of data or when we want to perform an operation a fixed number of times.

For example, imagine we have an array of numbers and we want to print each number on the console. Instead of manually writing a console.log statement for each number, we can use a loop to iterate through the array and print each value.

JAVASCRIPT
1const numbers = [1, 2, 3, 4, 5];
2
3for (let i = 0; i < numbers.length; i++) {
4  console.log(numbers[i]);
5}

In this example, we use a for loop to iterate through the numbers array. The loop starts with an initialization step (let i = 0), a condition (i < numbers.length), and an increment step (i++). The loop continues as long as the condition is true and allows us to access each element of the array using the index i.

Loops provide a powerful mechanism for automating repetitive tasks and iterating over data structures. They are fundamental in many programming languages, including JavaScript.

Now it's your turn to practice using loops. Try writing a for loop to print the numbers from 1 to 10 on the console.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment