Loops in JavaScript


It's time for another JavaScript lesson! This time we're looking at iterative statements, or loops that repeat a task until a condition is met. In JS, those statements come in the same two base formats as we've seen in Java, for and while. We'll look at the basic syntax of those two statements as well as variations like forEach, for...in, for...of, do...while, and loop control statements like break and continue. As a bonus, even though these aren't concepts we've covered in Java, they apply to it as well, so double the knowledge!

For Loops

Syntax

We know the basics of how a for loop works from our experience with Java. Fortunately, the syntax is very similar.
for ([initial expression]; [condition]; [increment expression]) {
     statement;
}
The major difference between JS and Java is that you don't have to identify the variable type in the initial expression when you declare the starting point.

What About The Enhanced For Loop?

Ah, yes! That was one of my first questions as well. Since JavaScript's syntax is based on Java, I wondered if we could use the enhanced for we learned about to loop through arrays in JS. Unfortunately, that isn't the case, though there is a solution that seems to be a good replacement... the forEach() method.

forEach() is called on an array and loops through every element in the array, executing the statement contained in the function. For an in-depth explanation, check out the Mozilla MDN web docs.

Syntax

arr.forEach(function callback(currentValue[, index[, array]]) {
     //your iterator
}[, thisArg]);


For...In Loop

The for...in loop allows you to loop through the properties of an object. For example, if we created a Car object with properties of Make, Model, Year, Color, etc., the for...in loop accesses each property in that object.

Syntax

for (variable in object) {
     statement
}

Here's an example using a person object, having the properties of firstName, lastName, age and eyeColor. As you can see, the i variable is accessing the property name (firstName) not the value in it. We must use the person[i] syntax to get the value held in the property.



You might be thinking, "Hey, can't I use this to loop through an array?" You can, but you shouldn't. The problem is that a for...in loop will return the name of user-defined properties in addition to the numeric indexes. Though as we'll see below, the for...of statement is designed for this purpose.

For...Of Loop

The for...of statement differs from the for...in statement in that it loops through the properties of iterable objects (String, Array, TypeArray, Map, Set). These are objects with built-in iterators, meaning they have implemented the @@iterator method. This includes the next() method, pointing to the next value in that object.

For example, if you used the for...of loop on a String object, like "hello", it would loop through each character in the string, because of the built-in iterator that points to the next value in the string and uses a boolean (done) to indicate when the end of the String has been reached.

Syntax

for (variable of object) {
     statement
}
Let's go back to the array from the forEach() example above and use that to demonstrate the difference between for...in and for...of.


As you can see in the for...of version we access the values in the array, in the for...in example it's the numeric indexes. Though as I stated above, in isn't the best practice to loop through arrays by index because user-defined properties can be accessed through for...in.

While Loops

Now let's dive in to loops that execute until a condition is met, otherwise known as while loops. Again, the syntax is similar to Java's, meaning you can omit the curly braces {} around the statement if it is just one line, but it's good practice to include them.

Syntax

while (condition) {
     statement;
}
In the example below, the first while loop only has one statement, so curly braces aren't necessary, unlike the second while loop.


Do...While Loop

The do...while loop is a version of the while loop where the statement is executed prior to checking the condition. This allows you to execute the statement once, even if the condition isn't met on the first iteration. It will stop after one execution in that case.

Syntax

do
     statement
while (condition);
As you can see in the below example, the second do...while loop executes once, even though the condition evaluates to false.

Loop Control Statements

Labeled Statements

We name methods so that we can call them in other methods, classes, etc. We can use labels to name statements, like for and while loops, in order to call them in other parts of our code. This is especially useful with the two concepts we will discuss below, break and continue statements.

Syntax

Label:
     Statement

Here I've labeled the while loop, countLoop, which I can refer to in other parts of my code.

Break Statement

We discussed breaks in my previous post about conditionals. In the same way that a break can be used to exit a switch statement when a condition is met, a break can exit a loop.

A break will exit the loop in which it is called. If it is part of nested loops, it will exit the innermost loop in which it appears, unless a labeled statement is called with the break. In that case, it will exit the loop identified in the break statement.

Syntax

break;   or
break label;
In the example below, the for loop runs through the array looking for the String "dog". Instead of looping through the entire array, the break statement exits the loop when the if statement's condition is met.

As you can see in the console, the loopCount variable demonstrates that the for loop only ran twice before exiting.


In this example, we have nested loops with a labeled outer loop, labelCancelLoops. Because the condition for both loops is (true), they would run indefinitely without the breaks, causing the program to crash.

The first break calls on the outer loop using the label, while the second break does not. So, the inner loop runs until it iterates 5 times and then breaks back to the outer loop. The outer loop runs until the inner loop condition with the labeled break is met. In this case, it stops in the second inner loop and exits completely.

Continue Statement

Finally, we have the continue statement. The continue statement is used to break out of the current iteration of a loop and jump back to the beginning. In a while loop, any loop code after a continue is skipped and we jump back to the while's conditional. In a for loop, any loop code after a continue is skipped and we proceed to the increment expression (e.g. i++).

Similar to the break statement in nested loops, the continue applies to the innermost enclosing loop, unless a label is used.

Syntax

continue;   or
continue label;
In this example, you can see how including the break changes the output of the while loop. On the third iteration of the loop with the break, the last two lines of code are skipped, so the running total (n) never has the three added in.
The continue statement can also call a labeled statement, like the break example above, which is handy when dealing with nested loops because you can specify which loop you want to jump to.

Note: As I mentioned in my previous post, I used the web-based JavaScript compiler, JSBin.com, to compile my code and show its output.

Comments

  1. I was going to say that I had a minor complaint that you didn't give an example of using a label, but then the next example did. You read my mind.

    Nice job!

    ReplyDelete

Post a Comment