A For Loop
is a control flow statement that allows code to be executed repeatedly. It’s a way to perform a task multiple times without having to write the same code over and over again.
Syntax of a For Loop
The syntax of a For Loop
in JavaScript is as follows:
for (initialization; condition; final expression) {
// code to be executed
}
- Initialization: This is where you initialize your counter variable, usually with a variable declaration. This part is executed once at the beginning of the loop.
- Condition: This is a boolean expression that is evaluated before each loop iteration. If it evaluates to
true
, the loop continues; if it evaluates tofalse
, the loop ends. - Final Expression: This is executed at the end of each loop iteration, typically used to update the counter variable.
Example of a For Loop
Here’s a simple example of a For Loop
that prints the numbers from 1 to 5:
for (let i = 1; i <= 5; i++) {
console.log(i);
}
In this example, i
is initialized to 1, the condition checks if i
is less than or equal to 5, and i
is incremented by 1 at the end of each loop iteration. The console.log(i)
inside the loop will print the numbers 1 through 5.
The For Loop
is a powerful tool in JavaScript, allowing you to write more efficient and cleaner code. It’s a fundamental concept that’s widely used in programming, so understanding how it works will greatly enhance your JavaScript coding skills.