-
Notifications
You must be signed in to change notification settings - Fork 2
Challenge Iterate With JavaScript For Loops
The most common type of JavaScript loop is called a for loop
because it runs for
a specific number of times.
var ourArray = [];
for(var i = 0; i < 5; i++) {
ourArray.push(i);
}
ourArray will now contain [0,1,2,3,4]
for(var i = 0; i < 5; i++) { // There are 3 parts here
There are three parts to for loop. They are separated by semicolons.
-
The initialization:
var i = 0;
- This code runs only once at the start of the loop. It's usually used to declare the counter variable (withvar
) and initialize the counter (in this case it is set to 0). -
The condition:
i < 5;
- The loop will run as long as this istrue
. That means that as soon asi
is equal to 5, the loop will stop looping. Note that the inside of the loop will never seei
as 5 because it will stop before then. If this condition is initiallyfalse
, the loop will never execute. -
The increment:
i++
- This code is run at the end of each loop. It's usually a simple increment (++
operator), but can really be any mathematical transformation. It is used to move the counter (i
) forward (or backwards, or whatever.
Learn to code and help nonprofits. Join our open source community in 15 seconds at http://freecodecamp.com
Follow our Medium blog
Follow Quincy on Quora
Follow us on Twitter
Like us on Facebook
And be sure to click the "Star" button in the upper right of this page.
New to Free Code Camp?
JS Concepts
JS Language Reference
- arguments
- Array.prototype.filter
- Array.prototype.indexOf
- Array.prototype.map
- Array.prototype.pop
- Array.prototype.push
- Array.prototype.shift
- Array.prototype.slice
- Array.prototype.some
- Array.prototype.toString
- Boolean
- for loop
- for..in loop
- for..of loop
- String.prototype.split
- String.prototype.toLowerCase
- String.prototype.toUpperCase
- undefined
Other Links