How to use for loop in Javascript
By FoxLearn 12/18/2024 7:07:26 AM 12
In JavaScript, a `for` loop is used to repeatedly execute a block of code a specific number of times.
It consists of three parts: initialization, condition, and iteration.
- Initialization: Sets the initial value of the counter variable.
- Condition: Specifies the condition that must be true for the loop to continue.
- Increment/Decrement: Updates the counter variable after each iteration.
Here is the syntax of a for
loop in JavaScript:
for (initialization; condition; increment/decrement) { // code to execute }
Let's break it down with an example:
for (let i = 0; i < 5; i++) { console.log(i); }
In this example:
- Initialization:
let i = 0
setsi
to an initial value of 0. - Condition:
i < 5
ensures the loop continues as long asi
is less than 5. - Increment:
i++
increases the value ofi
by 1 after each iteration.
The code inside the loop (in this case, console.log(i)
) will execute repeatedly until the condition becomes false, printing the value of i
to the console in each iteration.
Categories
Popular Posts
11 Things You Didn't Know About Cloudflare
12/19/2024