for keyword and requires three parameters enclosed in parentheses:
Here's a breakdown of these parameters:
- Initialization: This is where you initialize a new counter used by the
forloop. It's executed only once.
- Condition: An expression checked before each iteration, similar to the
- Increment/Decrement: Operations performed on the counter at the end of each loop iteration.
Iteration in loops refers to repeating a block of code a certain number of times or until a specific condition is met. Each time the block of code is executed, it's considered one iteration.
Let's illustrate this with an example:
In this example:
let i = 1: Initialization, where we create the variable
forloop. This operation executes once.
i < 5: Condition, checked before each iteration.
i++: Increment expression, executed after each iteration.
console.log("Loop iteration:", i);: Body of the
Each step in the loop can be described as follows:
Step 2 repeats until the condition becomes
It can be beneficial to consider a diagram to gain a clearer understanding of how the loop operates.
You can also use decrement in the
for loop, as shown here:
for loop counter is unique to its scope, so you don't need to worry about the counter name conflicting with other variables:
Different expressions for Increment/Decrement operations can be used as well:
Comparing the for and while loops
while loops, the
for loop is often simpler and more concise. Here's an example of equivalent loops:
In this comparison, the
for loop is more straightforward and occupies less code space. Additionally, the
for loop automatically clears the counter variable (in this case,
i) after execution.
Everything was clear?