Creating a for loop and a while loop in JavaScript using below simple example:
// Example: Printing numbers from 1 to 5 using a for loop
for (let i = 1; i <= 5; i++) {
console.log(i);
}
In this example, the for loop iterates over the values of i
from 1 to 5. It prints the value of i
in each iteration using console.log()
.
While Loop:
// Example: Printing numbers from 1 to 5 using a while loop
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
In this example, the while loop checks the condition i <= 5
before each iteration. It prints the value of i
and increments it by 1 (i++
) within each iteration.
Both the for loop and the while loop are used for repetitive execution of code. The main difference is that the for loop has a built-in initialization, condition, and increment/decrement in a single line, whereas the while loop requires manual initialization and modification of the control variable within the loop block.
- Log in to post comments