Mastering JavaScript | FOR LOOP
The for loop is a powerful tool that allows us to iterate over a block of code multiple times. It consists of three components: initialisation, condition, and increment. Let's see how it works:
1
2
3
for (let i = 0; i < 5; i++) {
// Code to be executed for each iteration
}
In this example, we initialise a variable i
to 0. The condition i < 5
specifies the limit for the loop. As long as the condition is true, the loop will continue executing. After each iteration, the increment i++
increases the value of i
by 1.
Inside the loop, we can perform any desired operations, such as printing values, manipulating data, or executing specific tasks. The loop will repeat the code block until the condition becomes false.
lets have another example to make thing much easier,
1
2
3
4
5
6
7
const numbers = [1, 2, 3, 4, 5];
const multipliedNumbers = [];
for (let i = 0; i < numbers.length; i++) {
multipliedNumbers.push(numbers[i] * 2);
}
console.log(multipliedNumbers);
This code creates an array of numbers. It then initialises an empty array called multipliedNumbers. Using a for loop, it iterates over each element in the numbers array and multiplies it by 2. The multiplied numbers are then pushed into the multipliedNumbers array. Finally, the multipliedNumbers array is logged to the console.