Javascript for loop
Created By: chatGPT
A for loop in JavaScript is used to execute a block of code a specific number of times. It consists of three main parts: initialization, condition, and increment. Let's break down each part for a clearer understanding.
Here's a simple example that demonstrates how to use a for loop to iterate through an array of numbers and log each number to the console.
In this example, we initialize the loop with const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
let i = 0
, which sets the starting index. The loop continues to execute as long as i < numbers.length
is true. After each iteration, we increment i
by 1 with i++
. During each loop, we access the current number using numbers[i]
and log it to the console.You can also use a for loop to calculate the sum of the numbers in the array. Here’s how you can do that:
This code snippet initializes a variable let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i]; // Add the current number to the sum
}
console.log(`The sum is: ${sum}`);
sum
to 0. Inside the loop, it adds each number from the numbers
array to sum
. Finally, it logs the total sum to the console using a template literal.Another common use of the for loop is to nested loops. For example, if you want to create a multiplication table:
In this snippet, the outer loop iterates through numbers 1 to 5. For each iteration of the outer loop, the inner loop also runs from 1 to 5, generating a multiplication result, and logs it to the console in a formatted string.for (let i = 1; i <= 5; i++) {
for (let j = 1; j <= 5; j++) {
console.log(`${i} x ${j} = ${i * j}`);
}
}