How to use for loop in Javascript
By Tan Lee Published on Dec 18, 2024 150
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.
- How to use sweetalert2
- How to Pass string parameter in an onclick function
- How to format number with commas and decimal in Javascript
- What does 'use strict;' means in Javascript
- How to detect if caps lock is pressed in Javascript
- How to create a Custom Event in Javascript
- How to Check if an Object Has a Property Properly in JavaScript
- How to convert an Uint8Array to string in Javascript
Categories
Popular Posts
Portal HTML Bootstrap
Nov 13, 2024
Freedash bootstrap lite
Nov 13, 2024
Motiv MUI React Admin Dashboard Template
Nov 19, 2024
K-WD Tailwind CSS Admin Dashboard Template
Nov 17, 2024