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
forloop is used to iterate over thenumbersarray. - The loop starts with
iset to 0, and iterates as long asiis less than the length of thenumbersarray. - The
console.logstatement inside the loop logs each element of thenumbersarray to the console.