JavaScript for loop
JavaScript for loop
In JavaScript, the for loop is used for iterating over a block of code a
certain number of times, or to iterate over the elements of an array.
console.log("Hello, world!");
// Output:
// Hello, world!
// Hello, world!
// Hello, world!
Flowchart of
JavaScript for loop
Example 1: Print Numbers From 1 to 5
for (let i = 1; i < 6; i++) {
console.log(i);
}
Run Code
Output
1
2
3
4
5
1 is printed.
1st i = 1 true
i is increased to 2.
2 is printed.
2nd i = 2 true
i is increased to 3.
3 is printed.
3rd i = 3 true
i is increased to 4.
4 is printed.
4th i = 4 true
i is increased to 5.
5 is printed.
5th i = 5 true
i is increased to 6.
let sum = 0;
const n = 100
// loop from i = 1 to i = n
console.log(`sum: ${sum}`);
console.log(fruits[i]);
Output
apple
banana
cherry
This loop iterates through the fruits array and prints each element to
the console.
JavaScript Loops
Loops in JavaScript are used to reduce repetitive tasks by repeatedly
executing a block of code as long as a specified condition is true. This
makes code more concise and efficient.
Suppose we want to print ‘Hello World’ five times. Instead of manually
writing the print statement repeatedly, we can use a loop to automate the
task and execute it based on the given condition.
for (let i = 0; i < 5; i++) {
console.log("Hello World!");
Output
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
// Code to execute
}
console.log("Count:", i);
Output
Count: 1
Count: 2
Count: 3
In this example
Initializes the counter variable (let i = 1).
Tests the condition (i <= 3); runs while true.
Executes the loop body and increments the counter (i++).
let i = 0;
while (i < 3) {
console.log("Number:", i);
i++;
Output
Number: 0
Number: 1
Number: 2
In this example
Initializes the variable (let i = 0).
Runs the loop body while the condition (i < 3) is true.
Increments the counter after each iteration (i++).
3. JavaScript do-while Loop
The do-while loop is similar to while loop except it executes the code
block at least once before checking the condition.
Syntax
do {
// Code to execute
} while (condition);
let i = 0;
do {
console.log("Iteration:", i);
i++;
Output
Iteration: 0
Iteration: 1
Iteration: 2
In this example:
Executes the code block first.
Checks the condition (i < 3) after each iteration.
Output
name : Ashish
age : 25
In this example:
Iterates over the keys of the person object.
Accesses both keys and values.
5. JavaScript for-of Loop
The for…of loop is used to iterate over iterable objects like arrays,
strings, or sets. It directly iterate the value and has more concise syntax
than for loop.
Syntax
for (let value of iterable) {
// Code to execute
}
console.log(val);
Output
1