Beginning AngularJS

(WallPaper) #1
ChApter 1 ■ JAvASCrIpt You Need to KNow

console.log("Looping finished");





The first thing we do is to print Looping started to the console. Then we enter the for loop. We enter the for
loop because of the conditional check, the bit that reads i < 5. Well, i (which is the counter) starts off at 0, so i < 5
evaluates to true. Only when i < 5 evaluates to false will the loop end and continue on to the next line of code, in
this case, the code that prints Looping finished to the console.
So, why would the variable i ever change its original value of 0? This is because each time the loop executes, it
also carries out the i++ logic. So, the counter goes up at each pass and eventually the loop ends.
The results follow. We will see the for loop in action again when I cover JavaScript arrays shortly.


Looping started
The current value of i is 0. We will loop again because 0 is less than 5
The current value of i is 1. We will loop again because 1 is less than 5
The current value of i is 2. We will loop again because 2 is less than 5
The current value of i is 3. We will loop again because 3 is less than 5
The current value of i is 4. We will loop again because 4 is less than 5
Looping finished


The while loop is a somewhat simpler version of the for loop. It doesn’t require as much setup, but it isn’t quite
as powerful (at least not without extra work). The basic structure of a while loop looks like this:


while( some value is true){
execture this block of code
}


The preceding isn’t real code, of course, but Listing 1-23 provides a basic demo of the while loop.

Listing 1-23. The while Loop in Action


<!DOCTYPE html>




JavaScript Primer




Free download pdf