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.

Aching back from coding all day?

Acupressure Mat & Pillow

Aching back from coding all day? Try Back Problems

Relieve your stress, back, neck and sciatic pain through 1,782 acupuncture points for immediate neck pain relief. Made for lower, upper and mid chronic back pain treatment, and improves circulation, sleep, digestion and quality of life.

$$ Check price
144.87144.87Amazon 4.5 logo(1,890+ reviews)

More Back Problems resources

Build modern and responsive webpages

The Modern Web

Build modern and responsive webpages Try Front-end

The Modern Web will guide you through the most important tools of device-agnostic web development, including HTML5, CSS3, and JavaScript. The plain-english explanations and practical examples emphasize the techniques, principles, and practices that you'll need to easily transcend individual browser quirks and stay relevant as these technologies are updated.

$ Check price
34.9534.95Amazon 4.5 logo(30+ reviews)

More Front-end resources

Ad