The for loop part 2

The For Loop



The example below creates a for loop that prints numbers 1 through 5.
for (i=1; i<=5; i++) {
document.write(i + "<br />");
}
Try It Yourself

In this example, Statement 1 sets a variablebefore the loop starts (var i = 1).
Statement 2 defines the condition for the loop to run (i must be less than or equal to 5).
Statement 3 increases a value (i++) each time the code block in the loop has been executed.

Result:
Statement 1 is optional, and can be omitted, if your values are set before the loop starts.
var i = 1;
for (; i<=5; i++) {
document.write(i + "<br />");
}
Try It Yourself

Also, you can initiate more than one value in statement 1, using commas to separate them.
for (i=1, text=""; i<=5; i++) {
text = i;
document.write(i + "<br />");
}
Try It Yourself

ES6 introduces other for loop types; you can learn about them in the ES6 course later.
Fill in the blanks to compose a valid for loop:

var i = 1;
 
 
 (k=1; k<10
 
 
 k++) 
 
 

   i += k;
}

Comments

Popular posts from this blog

Introducing object part 3

Comparison Operators part 2

Module 2