These free mini-courses will give you a strong foundation in web development. Track your progress and access advanced courses on HTML/CSS, Ruby and JavaScript for free inside our student portal.
Scroll down...
Are you ready to learn about looping? Are you ready to learn about looping? Are you ready to learn about looping? Are you ready to learn about looping? Break.
But first, we must once again return to our dear friend, Codecademy. Go through the lessons in both the ’For’ Loops in JavaScript and ’While’ Loops in JavaScript sections and then hurry back. We will miss you.
for
loops is one of the most common looping constructs, despite being somewhat unsightly. We'll cover the much friendlier forEach
in an upcoming lesson.
A for
loop has three steps:
This pattern is used constantly so it's worth becoming familiar with. Just about every major language uses it as well:
for ( var i = 0 ; i < 5 ; i++ ) {
console.log("in the " + i + " iteration");
}
A while
loop will execute its block of code (the bit of code supplied within its trailing curly braces) until the provided predicate (the statement inside of the parentheses) returns false:
var i = 0;
while ( i < 100 ){
// do stuff
i++;
}
// combining the conditional with the
// incrementer, which here increments
// BEFORE it is evaluated. Feel free to
// use this syntax elsewhere, though it
// is a bit atypical
var i = -1;
while ( ++i < 100){
// do stuff
}
// There's also a less popular do-while
// loop which executes the condition after
do {
// Even though the condition evaluates to false
// this loop's body will still execute once.
console.log( "Hi there!" );
} while ( false );
Break a loop with break
or jump to the next iteration with continue
:
for ( var i = 0; i < 10; i++ ) {
if ( itIsUnimportant(i) ) {
continue;
}
// The following statement will only be executed
// if the function "itIsUnimportant" returns false
console.log( "I have been reached" );
}
The only "gotchas" when working with looping in JavaScript are:
0
and ""
are falsy tooOnce you've hammered those home and build up your for
looping skills, it's all gravy.