In this section, we will learn what the while loop is and how to use it in JavaScript.
What is while loop?
Sometimes we need to iterate through a set of instructions until a condition is met.
Via the `while` loop, we can define a condition and a block of code. As long as the result of the condition is `true` the execution engine will run the body (the block) of that `while` loop.
For example, let’s say we have a variable named `alpha` and the initial value of this variable is `a`. There’s a block of code that if we run it, it will increase the value of this variable by one. So every time we run that block of code, the value of this `alpha` variable changes to the next alphabet character (b, c, d and e etc.).
What we want here is a loop that can iteratively execute that block until the value of the `alpha` variable reaches the value `z`.
This is a situation where we can use the `while` loop statement.
while Loop Syntax:
This is the syntax of the while-loop in JavaScript:
while (condition) { // the code block to be executed }
`while`: First, we use the keyword `while` to create a `while` loop.
`( )`: The pair of parentheses that comes after the keyword is used to put the condition of the loop. The condition here can be like, while the value of a variable is not equal to something (the result is true then), iterates the loop.
Note: as long as the result of the condition is true, the body of the `while` loop will run.
Also the `true` and `false` variables can be used as the value of the condition. Of course, in such case, the value `true` will cause the loop to repeat itself infinitely (unless we use statements like `break;` or `return;`). Also, if we put the value `false` as the condition of the loop, the body will not run at all because the condition is already false!
Besides the values `true` and `false`, we can use other primitives and objects. In that case, the execution engine will execute the `ToBoolean` operation on that value to coerce it into a value of type `Boolean`.
Example:
while (100){…} // the result of the condition is true
`{ }`: The body of the while loop starts from the opening brace `{` and ends right at the closing brace `}`.
Note: every time the engine executes the body, the condition will be checked again.
Example: using while loop in Java
let character = 'a'; let arr = new Array(); while(character !='z'){ arr.push(character); let code = character.charCodeAt(0); code++; character = String.fromCharCode(code); } console.log(arr);
Output:
["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y"]
Here, the condition of the while loop is to check whether the value of the `character` variable is equal to the value `z`. So, for as long as the condition of the loop is true (which means the value is not equal yet) the body will be executed over and over again.
Note: as mentioned before, every time the body is executed, the condition will be checked again.
In the body of this loop, we’ve used two methods:
- charCodeAt(): in its section we’ve explained what this method does, but in short it will return the number representation of the target character.
Note: we used this method because we can’t apply the `++` operator on a non-Number value.
- fromCharCode(): this method is used to take a Unicode number and it will return its String representation.
Note: basically in the body of the loop, we used `++` operator to increase the value of the `character` variable to ensure the loop will not run indefinitely.
At the end when the value of the `character` variable reached to the `z` value, the condition of the `while` loop returns false and so the body is skipped in that case and the statement after this loop which is `console.log(arr);` is executed by the execution engine.
This is an important note to remember: Design the body of a loop in a way to affect the condition of the loop so it doesn’t run forever!
JavaScript while break
We can use the `break` statement in the body of a while loop to break that loop before it gets finished if it’s needed.
Note: the break statement is explained in greater details in the future lessons, but in short, it will break a loop and send the execution engine to run the statements after the body of the target loop.
Example: using break statement in JavaScript while loop
var num = 0; while(true){ num++; if (num ==100){ break; } } console.log(`The final value of the num variable is: ${num}`);
Output:
The final value of the num variable is: 100
As you can see, the condition of this loop is set to true, and that means the while loop should execute infinitely (because the condition is always true). But you can see that after just looping 100 times, the loop broke and the statement that was after this loop gets executed. This is because of the `break` statement that we’ve set in the `if` statement of this loop which triggered when the value of the `num` variable reached the value of the 100.
JavaScript continue Statement
Inside the body of the while loop, we can use the `continue` statement as well.
This statement basically tells the loop to skip the current iteration and start the next one.
Note: the continue statement is covered in later sections.
Example: using continue statement in JavaScript while loop
var num = 0; while(num<100){ num++; if (num <95){ continue; } console.log(num); } console.log("End");
Output:
96 97 98 99 100 End
Here the execution of the `console.log()` method in the body of the while loop is skipped for the first 95 iteration because of the call to the `continue` statement.
JavaScript Infinite Loop
Infinite loop means a loop that never stops running!
In order to create such loop using the `while` statement, all we need to do is to put the boolean value `true` as the argument of the while statement. After that, the body will be executed infinitely because the condition of the loop is always true!
Note: for the majority of cases, we don’t need to have a loop that runs infinitely! For this reason, if the condition of a loop is set to true, then it’s best to use an if statement and the `break` or `return` to break the loop at some point.
Example: creating infinite loop in JavaScript via while loop
var num = 0; while(true){ num++; if (num ==100){ break; } } console.log(`The final value of the num variable is: ${num}`);
Output:
The final value of the num variable is: 100
In this example, we have an infinite while loop because the condition is set to true! But then inside the body of this loop, we’ve defined a condition that if the value of the `num` variable was equal to the value 100, then call the `break` statement. This way we’re assured that the program won’t continue to execute forever!
Difference between while and do while
Other than the `while` loop, there’s another conditional loop that is called `do while`. The work of this conditional loop is pretty much the same as the while loop, but with a subtle difference!
The `while` loop first checks the condition we set for it and then runs its body! This means there’s a chance that the body of this loop might never run if the condition is false in the first place!
On the other hand, the `do while` loop first runs its body (at least once) and then checks the condition set for it. This will guarantee the execution of the loop at least once.
while Loop vs for Loop
Both the `for loop` and while loop are capable of running a block of code for x number of times, but the design of `for loop` is more focused towards creating loops that should run for a specific number of times. On the other hand, the `while` loop is designed to run a block of code as long as a condition is met! So the number is not of the focus when using the `while` loop.
Note: remember, both while and for loop still are capable of doing the same tasks, but their main difference is in the design purpose.