04. Loops

Loops are used to repeat a block of statements a set number of times.

for loops

When using a for loop, you instantiate a counter variable (initialization), set a condition for the loop to run until (condition), then set some increment/decrement operator for the counter (update).

for (var i = 0; i < 10; i++) {
  // code statement blocks here to run 10 times.

Here is a list of the steps per a for loop:

  1. Initialize variable i to 0.
  2. Check if i is less than 10. If not, exit the loop.
  3. Run the code statements.
  4. Increment i.
  5. Go back to step 2 and repeat.

while loops

while loops are similar, but the only parameter needed is the condition. Before JavaScript runs the code block within this loop, it makes sure that the condition evaluates to true.

while (i < 10) {
  // Execute some commands
  i += 2; // update your counter, otherwise infinite loop.

do-while loops

To ensure that your code runs at least once, you may use a do-while loop. The do-while loop first executes, then checks your conditional statement.

do {
  // Execute a command block
  x += 1;
} while (x < 10);

break and continue

Two extremely helpful one-word statements used exclusively in loops are break and continue. The former exits out of the loop, while the latter pushes the JavaScript interpreter back up to the conditional statement.

Build modern and responsive webpages

High Performance Web Sites

Build modern and responsive webpages Try Front-end

Want your web site to display more quickly? This book presents 14 specific rules that will cut 25% to 50% off response time when users request a page. Author Steve Souders, in his job as Chief Performance Yahoo!, collected these best practices while optimizing some of the most-visited pages on the Web.

$ Check price
29.9929.99Amazon 4.5 logo(63+ reviews)

More Front-end resources

Aching back from coding all day?

Foam Seat Cushion

Aching back from coding all day? Try Back Problems

This foam seat cushion relieves lowerback pain, numbness and pressure sores by promoting healthy weight distribution, posture and spine alignment. Furthermore, it reduces pressure on the tailbone and hip bones while sitting. Perfect for sitting on the computer desk for long periods of time.

$ Check price
99.9599.95Amazon 4.5 logo(9,445+ reviews)

More Back Problems resources