Problem Statement
What is the correct syntax for a for loop?
Explanation
The correct syntax has three parts inside parentheses: initialization, condition, and increment.
Initialization runs once at the start. Condition is checked before each iteration. Increment runs after each iteration.
Use let instead of var for the loop variable due to block scoping.
The code block to execute goes inside curly braces after the parentheses.
For loops are ideal when you know how many times to iterate.
Code Solution
SolutionRead Only
// Basic for loop
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
// Loop through array
const fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// Reverse loop
for (let i = 5; i > 0; i--) {
console.log(i); // 5, 4, 3, 2, 1
}
// Step by 2
for (let i = 0; i < 10; i += 2) {
console.log(i); // 0, 2, 4, 6, 8
}
// Multiple variables
for (let i = 0, j = 10; i < 5; i++, j--) {
console.log(i, j); // 0 10, 1 9, 2 8, 3 7, 4 6
}
// Nested loops
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
console.log(i, j);
}
}