JavaScript / JavaScript Control Structures

Mastering JavaScript Loops

In this tutorial, we will dive into JavaScript loops, including For, While, and Do-While loops. These loops are instrumental in executing blocks of code repeatedly based on specif…

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explores conditionals, loops, and control flow in JavaScript.

1. Introduction

In this tutorial, we aim to help you master JavaScript loops, namely For, While, and Do-While loops. These loops are a fundamental part of JavaScript and programming in general, as they allow you to execute blocks of code repeatedly based on specific conditions. By the end of the tutorial, you will have a deep understanding of how these loops work and how to implement them in your projects.

Before starting, you should have a basic understanding of JavaScript, including variables, data types, and control structures.

2. Step-by-Step Guide

JavaScript provides several ways to perform repetition or looping. The most common are for, while, and do...while loops.

For Loop

A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for loop.

for ([initialization]; [condition]; [final-expression])
   statement
  • Initialization: Run before the first execution on the loop. This expression usually initializes one or more loop counters.
  • Condition: Defines the condition for executing the loop.
  • Final expression: Executes at the end of each loop execution. It is usually used to increment the counter.

While Loop

A while loop executes its statements as long as a specified condition evaluates to true. If the condition becomes false, statement within the loop stops executing and control passes to the statement following the loop.

while (condition)
  statement

Do-While Loop

The do...while loop is similar to the while loop. The loop will always be executed at least once, even if the condition is false, because the code block is run before the condition is tested.

do {
   statement
} while (condition);

3. Code Examples

Example: For Loop

// Initialize counter to 1
// Continue looping while counter is less than or equal to 5
// Increment counter after each loop
for (let counter = 1; counter <= 5; counter++) {
  console.log(counter); // Output the counter
}

The expected output will be numbers from 1 to 5, each number in a new line.

Example: While Loop

let counter = 1; // Initialize counter to 1

// Continue looping while counter is less than or equal to 5
while (counter <= 5) {
  console.log(counter); // Output the counter
  counter++; // Increment counter after each loop
}

The expected output will be numbers from 1 to 5, each number in a new line.

Example: Do-While Loop

let counter = 1; // Initialize counter to 1

// Continue looping while counter is less than or equal to 5
do {
  console.log(counter); // Output the counter
  counter++; // Increment counter after each loop
} while (counter <= 5);

The expected output will be numbers from 1 to 5, each number in a new line.

4. Summary

In this tutorial, we've learned about JavaScript loops, including For, While, and Do-While loops. We've seen how they can execute code blocks repeatedly based on specific conditions, and we've looked at examples for each one.

Next steps might include studying more complex loop structures, and understanding how to use break and continue statements to control loop execution. For additional resources, consider visiting Mozilla Developer's Network Loop and Iteration guide.

5. Practice Exercises

Here are some practice exercises:

  1. Write a for loop that counts down from 10 to 1.
  2. Write a while loop that outputs every 2nd number from 1 to 10.
  3. Write a do...while loop that outputs the squares of numbers from 1 to 5.

Solutions:

  1. For Loop:
for (let counter = 10; counter >= 1; counter--) {
  console.log(counter);
}

This loop starts at 10 and decrements the counter until it reaches 1.

  1. While Loop:
let counter = 1;
while (counter <= 10) {
  if (counter % 2 == 0) console.log(counter);
  counter++;
}

This loop checks each number from 1 to 10, and only outputs it if it's even (i.e., divisible by 2).

  1. Do-While Loop:
let counter = 1;
do {
  console.log(counter * counter);
  counter++;
} while (counter <= 5);

This loop outputs the square of each number from 1 to 5.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

Age Calculator

Calculate age from date of birth.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help