The for loop is a control flow statement in JavaScript that allows you to execute a block of code repeatedly. The loop has three optional expressions, enclosed in parentheses, which are separated by semicolons.
for (initialization; condition; increment/decrement) {
// code to be executed
}
- Initialization: This expression is executed only once before the loop starts. It is typically used to initialize a counter variable.
- Condition: This expression is evaluated at the beginning of each loop iteration. If the condition is true, the loop continues; if it is false, the loop ends.
- Increment/decrement: This expression is executed at the end of each loop iteration. It is typically used to update the counter variable.
JavaScript for loop example
Simple example code loop from 0 to 4.
<!DOCTYPE html>
<html>
<body>
<script>
for (let i = 0; i < 5; i++) {
console.log("i value = ", i);
}
</script>
</body>
</html>
Output:
Loop through an array
const arr = [1, 2, 3];
for (let i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Loop through an object’s properties
const obj = {a: 1, b: 2, c: 3};
for (let prop in obj) {
console.log(`${prop}: ${obj[prop]}`);
}
JavaScript Infinite for loop
If the test condition in a for
loop is always true
, it runs forever (until memory is full). For example,
// infinite for loop
for(let i = 1; i > 0; i++) {
// block of code
}
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version