JavaScript For Kids For Dummies
Book image
Explore Book Buy On Amazon

The most commonly used types of loops in JavaScript are the for loop and the while loop. However, there are a couple other, more specialized, types of loops you may need to use.

for...in

The for...in loop performs statements repeatedly, once for each item inside an object or an array. For example, the following object has three properties in it:

var mySalad = {tomatoes: 3, cucumber: 2, lettuce: 1};

Using the for...in loop, you can run a block of code once for every property in this object. For example, to print out all the properties of the object, you would use the following loop:

for (var veggie in mySalad) {
 console.log(veggie + " is in my salad.");
}

The result, when run in the JavaScript console, is shown below.

image0.jpg

do...while loops

The do...while loop works almost the same as a while loop, except that it always runs its statements at least once. For example, here’s a snippet of JavaScript code that contains a while loop that will never run, because the condition clearly isn’t true:

var age = 15;
while (age > 100) {
 // do something
}

By using a do...while loop, you can guarantee that the statements will run once, even if the condition is never true. For example:

var age = 15;
do {
 // do something
} while (age > 100);

It’s possible to do anything you need to do in JavaScript with just one or two different types of loops. But if you know how to use all of the different loops, you can write code that’s easier to understand with fewer statements!

About This Article

This article is from the book:

About the book authors:

Chris Minnick and Eva Holland are experienced web developers, tech trainers, and coauthors of Coding with JavaScript For Dummies. Together they founded WatzThis?, a company focused on training and course development.

This article can be found in the category: