Basic Syntax: Looping

Repeating tasks and iterating collections with JavaScript loops.

Scroll down...

Content

Resources

Comments

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.

Codecademy Interlude

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.

Looping

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:

  1. Initialize any variables you'll need (you can do multiple at once)
  2. Set up the conditional to be evaluated on each iteration
  3. Set up a statement to be run at the end of each iteration

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" );
}

Wrapping Up

The only "gotchas" when working with looping in JavaScript are:

  1. Remember that 0 and "" are falsy too
  2. Mind those parentheses and braces!

Once you've hammered those home and build up your for looping skills, it's all gravy.



Sign up to track your progress for free

There are ( ) additional resources for this lesson. Check them out!

There are no additional resources for this lesson just yet!

Sorry, comments aren't active just yet!

Next Lesson: Basic Syntax: Control Flow