A loop is a programming construct that repeats a block of code until a certain condition is met. It allows for the efficient repetition of tasks, such as iterating over a collection of items or executing a set of statements multiple times.
Loops are commonly used for iterating over arrays, processing input, and implementing repetitive tasks.
Example:
Here’s an example of a for
loop in JavaScript that iterates over an array and logs each element to the console:
const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
In this example:
- The
for
loop is used to iterate over thenumbers
array. - The loop starts with
i
set to 0, and iterates as long asi
is less than the length of thenumbers
array. - The
console.log
statement inside the loop logs each element of thenumbers
array to the console.