Friday , 17 November 2017
Home / Programming / JavaScript / While Loop – JavaScript Tutorial
While Loop
While Loop

While Loop – JavaScript Tutorial

This tutorial is part of the JavaScript tutorial series for beginners. To view the whole list of tutorials available and the order in which you should follow them, then click here.

We’ll be continuing with loops by learning about the while loop. The while loop is another way of looping through a block of code while a certain condition is true. Before we get started, let’s talk about iterations for a second

Iterations

An iteration is the technical term for a process that repeats itself. In the programming world, every time a loop successfully runs, then that’s considered an iteration.

Creating A While Loop

Clear out your script and update your code to this.

A couple of things going on here. We create 2 variables called i and total. Both of these values are assigned 0. Next, we create a while loop. A while loop is structured similar to the for loop. There’s one main difference. A while loop does not have an initializer and does not have an increment. It’s made up of 2 parts. The first part is inside the parenthesis. This is where you insert the conditional. If this condition is true, then the loop runs. Inside the curly brackets is the second part. This is where you execute all your code.

Since you don’t have an increment or an initializer, we have to create these outside and inside the loop. Inside our loop, we add 10 to the variable total and increment i by 1. Our loop will run as long i is less than 10. Lastly, we alert the final value of total.

While Loops vs For Loops

Both of these loops are useful for certain situations. A for loop is mainly used for situations where you know exactly how many times you want a loop to run. A while loop is used when you’re uncertain when you want to break out of it. We haven’t talked about objects yet, but soon you’ll see how more flexible a while loop can be in unknown situations.

Conclusion

You’ll find yourself using both loops. You’re more than welcome to stick to one type of loop. In our next tutorial, we’ll talk about a variation of the while loop.

About Jasko Koyn

Check Also

Try-Catch Statement

Try-catch Statement – Advanced JavaScript Tutorial

The try-catch statement is a unique way to handle errors. When errors occur, usually it …

Leave a Reply

Your email address will not be published. Required fields are marked *

ULTIMATE WORDPRESS DEVELOPMENT COURSE
Want to learn how to create your own custom WordPress plugins and themes? Check out my course!
Get 93% off my course. You'll also learn how to integrate WooCommerce and BuddyPress into your projects. This is a limited time offer
Yes, I would like to get 93% off your course!
No Thanks!
close-link