Back to Course

Introduction to JavaScript

0% Complete
0/0 Steps
  1. JavaScript: Basics
    9Topics
    |
    10 Quizzes
  2. JavaScript: Variables
    9Topics
    |
    10 Quizzes
  3. JavaScript: Conditional Statements
    10Topics
    |
    11 Quizzes
  4. JavaScript: Functions
    10Topics
    |
    11 Quizzes
  5. JavaScript: Scope
    6Topics
    |
    7 Quizzes
  6. JavaScript: Arrays
    11Topics
    |
    12 Quizzes
  7. JavaScript: Loops
    8Topics
    |
    9 Quizzes
  8. JavaScript: High Order Functions
    3Topics
    |
    3 Quizzes
Lesson 7, Topic 6
In Progress

JavaScript: While Loop

Yasin Cakal 20 Nov 2021
Lesson Progress
0% Complete

You’re doing a fantastic job! We’ll show you how to use a different kind of loop: the while loop. Let’s begin by converting a for loop to a while loop:

// A for loop that prints 1, 2, 3 , 4 and 5
for (let firstCounter = 1; firstCounter <=5; firstCounter++){
  console.log(firstCounter);
}
 
// A while loop that prints 1, 2, 3 , 4 and 5
let secondCounter = 1;
while (secondCounter <=5) {
  console.log(secondCounter);
  secondCounter++;
}

Let’s take a closer look at what’s going on with our while loop syntax:

  • Before the loop, the secondCounter variable is declared. Because it’s in the global scope, we can use it inside our while loop.
  • The keyword while is used to start our loop, followed by our stopping condition, or test condition.
  • Before each loop round, this will be evaluated. The block will continue to run while the condition evaluates to true. The loop will end when it evaluates to false.
  • Next, we have the code block for our loop, which prints secondCounter to the console and increments it.

What if we didn’t increment secondCounter within our block? If we didn’t include this, secondCounter‘s value would always be 1. As a result, the testing condition secondCounter<=5 would always evaluate to true, and our loop would never stop functioning! Remember that this is referred to as an infinite loop, and we want to avoid it at all costs. Infinite loops can consume all of your computer’s processing power, causing it to shut down.

So you’re probably wondering when you should use a while loop. When we know how many times the loop should run, the syntax of a for loop is ideal, but we don’t always know this ahead of time. while loops are the best choice when we need a loop to execute an undetermined number of times.

Responses

Leave a Reply

%d bloggers like this: