While Loops
Introduction
So far, we have learned about the if loop, and the different ways we can incorporate conditionals into it to solve our problems. However, this is not the only type of loop that Javascript offers us. In this lesson, we will take a look into the while loop.
Overview
By the end of this lesson, you should be able to:
- Understand what while loops are and how they work
- Understand how to incoporate conditional statements in while loops
- Use and understand the
break
statement - Start using while loops to solve problems
While Loops
Just like if loops, while loops also have their own syntax. It is very similar to one of an if loop in the fact that there is a condition and some code to execute while that condition is true. Take a look:
while (condition is true) {
-- execute some code --
}
Just like with the if loop, we also wrap our condition in parentheses and put our inner code in curly brackets.
Using conditions
Let’s look at a really basic example of a while loop. In this example, the code will keep running as long as number
is less than 10
.
let number = 0
while (number < 10) {
console.log(i)
number++ // This just increases "number" by 1 each time the loop runs
}
So what is this code going to log? Go ahead and try to copy the code into an editor, see what it logs!
It should log all the numbers between 0
to 9
. In the loop, we are also increasing the value of our variable number
by 1
, so after 9 loop iterations, it will have reached 10. This loop will log all the numbers between 0
– 9
, but what if we want to get all the numbers between 0
– 9
. Here is how to do it:
let number = 0
while (number <= 10) {
console.log(i)
number++ // This just increases "number" by 1 each time the loop runs
}
Go ahead and put this in your code editor. As you can see, all the numbers between 0 – 10, are now being logged. This is because we now changed our conditional so that the loop will stop running when number
is greater than OR equal to 10
. Instead of 9 iterations, it will loop 10 times.
Now what if we wanted to get all the numbers between 4
and10
? How would we do that? We can just change the value of our original variable number
like this:
let number = 4
while (number <= 10) {
console.log(i)
number++ // This just increases "number" by 1 each time the loop runs
}
Infinite Loops
Notice how in all the previous examples, we are incrementing our variable number
by 1? The reason why we do this is to make sure our code does not run in an infinite loop. Here is an example of some code that runs an infinite loop. (Do NOT run this!)
let number = 0
while (number < 10) {
console.log(number)
}
// This code results in an INFINITE loop
// This is due to the while loop ALWAYS being true since number is never being changed
As you can see, the above code results in an infinite loop since number
is always going to be less than 10
. The while loop will run forever and never stop running. Infinite loops can be dangerous because they can crash your program. Always make sure that your while loops end in some way or another!
Loops with Conditionals
By now, you should understand the very basics of while loops. So far, we have only used simple less than and greater than conditionals. Let’s see some while loop examples with different conditional statements!
Our next example will log all the even numbers between 0 and 100. Here is how we do it:
let number = 0
while (number <= 100) {
if (number % 2 === 0) {
console.log(number)
}
number++ // Incrementing number by 1 each time the loop runs!
}
Here, we are using the modulus operator (%
) to check whether a number is even. (If you don’t know what the modulus operator is, refer back to this lesson on JS arithmetic). We are checking whether there is a remainder after dividing a number by two. If the remainder is equal to 0
,we know its even.
What if we wanted to log all the multiples of 3
instead of 2
? Here is how we do it:
let number = 0
while (number <= 100) {
if (number % 3 === 0) {
console.log(number)
}
number++ // Incrementing number by 1 each time the loop runs!
}
Just like the previous example, we are using the modulus operator to check if our number is divisble by 3.
Now let’s understand some more complex examples of while loops using lists. What if we wanted to print out every single item of a list? You could just individually console.log(listitem)
, but that takes a long time and is inefficient. Here is how we would do it with a while loop:
// Declaring our list and variable "index"
let list = [true, "bananas", 3781, "randomString"]
let index = 0
// Looping through the list
while (index < list.length) {
console.log(list[index]) // Logging the index of each item in the list
index++ // incrementing "index" by 1
}
This might look a bit confusing, so let’s go through it step by step. Our conditional is index < list.length
. What we are saying here is that while index
is less than list.length
(length of our list), keep running. Once index
reaches thelist.length
, our loop will stop running.
Next, we just log each index of list
using list[index]
(if this is confusing, refer back to this lesson on list methods) and then increase index by one using index++
. This allows us to print out every item from a list.
Let’s look at another example. In this one, we are adding 5 to each value in our list!
let numlist = [1,2,3,4,5]
let index = 0
while (index < numlist.length) {
numlist[index] = numlist[index] + 5 // Adding 5 to each index of our list
index++
}
console.log(numlist) // Logs [6, 7, 8, 9, 10]
In this example, we are taking each index of our list numlist
and adding 5 to it. You can see how it works in line 5. We find the index, and then set the value of that index to its original value plus 5.
As you might have seen so far, while loops are really powerful and they have a ton of use cases. In the next section, we will learn about the break
command and how we can utilize it within our loops.
The "break" statement
Sometimes when we are using a while loop, we want to stop the loop at a certain point. Javascript allows us to use something called the break
command, which will completely stop a loop while it’s running. That might be a bit confusing to understand, so let’s look at an example:
// Declaring Variables
let numlist = [71, 39, 6, 419, 10, 21, 11, 735]
let index = 0
// Defining loop
while (index < numlist.length) {
if (numlist[index] === 10) {
break; // Stop the loop if value in numlist equals 10
} else {
index++ // If value is not ten, keep searching through the list
}
}
console.log(index) // Logs "4"
In this example, we are searching through our list numlist
to find the number 10. Once we do find number 10, we will break
or stop the loop from continuing to run. The break
command in JavaScript is used to terminate a loop or switch statement immediately. They can be useful if you want your loop to stop running after finishing a certain task.
Let’s look at one more example.
let number = 0
while (number < 100) {
if (number === 24) {
break; // Break from loop once number is equal to 24
} else {
number++ // Incrementing number by 1
}
}
In this example, we are incrementing our variable number
by 1 until we reach 24. Then the loop will stop.
Hopefully by now, you understand the basics of while loops and how to incorporate conditionals and the break
keyword within them. As you start working on projects and writing more code, there are times when you want to use a while loop. This lesson served as a basic introduction to while loops. If you’re still confused, some other materials will be linked in the practice section!
Practice
Now that you have a good understanding of the basics of while loops
, let’s practice using them with some exercises! We’ll provide you with some starter code and a hint in case you get stuck. If you need more help, don’t hesitate to join our Discord server.