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.
for (let i = 0; i < 3; i++) {
console.log("Hello, world!");
// Output:
// Hello, world!
// Hello, world!
// Hello, world!
JavaScript for loop Syntax
The syntax of the for loop is:
for (initialExpression; condition; updateExpression) {
// for loop body
}
initialExpression - Initializes a counter variable.
condition - The condition to be evaluated. If true, the body of
the for loop is executed.
updateExpression - Updates the value of initialExpression.
Once an iteration of the loop is completed, the condition is evaluated
again. The process continues until the condition is false.
Flowchart of JavaScript for Loop
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
In this example, we have printed numbers from 1 to 5 using a for loop.
Here is how this program works:
Iteration Variable Condition: i < 6 Action
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.
6th i = 6 false The loop is terminated.
Example 2: Display Sum of n Natural
Numbers
// program to display the sum of natural numbers
let sum = 0;
const n = 100
// loop from i = 1 to i = n
// in each iteration, i is increased by 1
for (let i = 1; i <= n; i++) {
sum += i; // sum = sum + i
console.log(`sum: ${sum}`);
// Output: sum: 5050
Initially, the value of sum is 0, while n has a constant value of 100.
Then, we iterate a for loop from i = 1 to n. In each iteration,
i is added to sum.
Then, the value of i is increased by 1.
When i becomes 101, the test condition becomes false and sum will be
equal to 0 + 1 + 2 + ... + 100 .
Iterate Through an Array
const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
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!
Let’s now discuss the different types of loops available in
JavaScript
1. JavaScript for Loop
The for loop repeats a block of code a specific number of times. It
contains initialization, condition, and increment/decrement in one line.
Syntax
for (initialization; condition; increment/decrement) {
// Code to execute
}
for (let i = 1; i <= 3; i++) {
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++).
2. JavaScript while Loop
The while loop executes as long as the condition is true. It can be
thought of as a repeating if statement.
Syntax
while (condition) {
// Code to execute
}
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++;
} while (i < 3);
Output
Iteration: 0
Iteration: 1
Iteration: 2
In this example:
Executes the code block first.
Checks the condition (i < 3) after each iteration.
4. JavaScript for-in Loop
The for…in loop is used to iterate over the properties of an object. It only
iterate over keys of an object which have their enumerable property set
to “true”.
Syntax
for (let key in object) {
// Code to execute
}
const obj = { name: "Ashish", age: 25 };
for (let key in obj) {
console.log(key, ":", obj[key]);
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
}
let a = [1, 2, 3, 4, 5];
for (let val of a) {
console.log(val);
Output
1
Choosing the Right Loop
Use for loop when the number of iterations is known.
Use while loop when the condition depends on dynamic factors.
Use do-while loop to ensure the block executes at least once.
Use for…in loop to iterate over object properties.
Use for…of loop for iterating through iterable objects.