JavaScript For Loop
JavaScript 'for' loop is the most compact form of looping. It includes the following three important parts:
- The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.
- The test statement which will test if a given condition is true or not. If the condition is true, then the code given inside the loop will be executed, otherwise the control will come out of The iteration statement where you can increase or decrease your counter.the loop.
- The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.
Syntax:
for (initialization; test condition; iteration statement) {
// Statements to be executed if condition is true
}
// Statements to be executed if condition is true
}
Try the following example to learn how a for loop works in JavaScript.
Example:
for (count = 0; count < 10; count++) {
document.write ("Current Count : " + count );
document.write ("<br />");
}
document.write ("Current Count : " + count );
document.write ("<br />");
}
Run Example
JavaScript for...in Loop
The for...in loop is used to loop through an object's properties. As we have not discussed Objects yet, you may not feel comfortable with this loop. But once you understand how objects behave in JavaScript, you will find this loop very useful.
Syntax:
for (variable_name in object) {
// statement or block to execute
}
// statement or block to execute
}
In each iteration, one property from object is assigned to variable_name and this loop continues till all the properties of the object are exhausted.
Try the following example to implement for...in loop:
Example:
var person = {fname:"John", lname:"Doe", age:25};
var var text = "";
var x;
for (x in person) {
text += person[x];
}
var var text = "";
var x;
for (x in person) {
text += person[x];
}
Run Example