Home

Advanced Looping with JavaScript

|
Updated:  
2016-03-26 7:38:15
|
JavaScript Essentials For Dummies
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 author:

Chris Minnick is an accomplished author, teacher, and programmer. Minnick authored or co-authored over 20 books, including titles in the For Dummies series. He has developed video courses for top online training platforms and he teaches programming and machine learning to professional developers at some of the largest global companies.

Eva Holland is an experienced web developer, tech trainer, and coauthor of Coding with JavaScript For Dummies. She is a co-founder of WatzThis?, a company focused on training and course development.