DEV Community

loading...
Cover image for JavaScript Made Easy: Part 12

JavaScript Made Easy: Part 12

dtetreau profile image David Tetreau Updated on ・2 min read

For Part 12, we will continue talking about loops. Last time we discussed a very important type of loop, the for/in loop. This time, we will switch gears and discuss the while loop. Open up your repl and code along!

While Loop Syntax

The while loop executes a statement as long as the condition is true. The syntax for the while loop is as follows:

while(condition) {
  statement
}
Enter fullscreen mode Exit fullscreen mode

This type of loop checks that a specified condition is true and then executes the statement or statements inside. Notice that this type of loop is different than some of the other types of loops.

With the for loop, there are conditions to be checked before the loop runs, but this process involves incrementing a variable and when the counter reaches a specified number, the loop stops running.

Example

Here's an example to get a better idea of how while loops work:

let schoolDaysLeft = 100; 
while(schoolDaysLeft >= 0) {
  console.log("There are " + schoolDaysLeft + " days left until summer break.");
  if(schoolDaysLeft > 0) {
  schoolDaysLeft--;
  } else if (schoolDaysLeft === 0){ 
  console.log("School is over!");
  break;
 }
}
Enter fullscreen mode Exit fullscreen mode

Notice that there was break inserted in the code when schoolDaysLeft was equal to zero. This keyword instructs the loop to stop running. In this example we:

  1. Initialized a variable which represents the number of days left until school is over.
  2. Created a while loop which checks a condition. The condition for the loop to run is that schoolDaysLeft is greater than or equal to 0.
  3. When the loop runs, it will console.log a string such as the following string: "There are 11 days left until summer break".
  4. The loop will check the conditionals (if and else if statements). If the schoolsDaysLeft variable has a value greater than zero, the variable will be decremented.
  5. If the loop equals zero there will be a message logged to the console that indicate school is over.

Conclusion

Take some time and practice making your own while loop. Try to make an infinite loop in your repl. This is a loop where the condition will always be true. These are to be avoided because they will cause issues, however you should become familiar with them.

I hope you have enjoyed this post! Please check out the entire "JavaScript Made Easy" series by David Tetreau. There will be a new post daily.

Discussion (1)

Some comments have been hidden by the post's author - find out more

Forem Open with the Forem app