This week in ng-club we are going to talk about loops. More specifically we will dive into the two most common types of loops (i.e. while loops and for loops).

The While Loop

The idea here is quite simple. Everything inside the while loop is executed again and again until the condition evaluates to false. So, for example:


// this will print "hello, world" forever since while is ALWAYS true
while (true) {
  console.log('hello, world');
}

// this will print out 1 2 3 4
var i = 1;
while (i < 5) {
  console.log(i);
  i = i + 1;
}

Whenever you make a while loop, you need to be extra careful that there will always be a point when the loop breaks (i.e. the condition is not true). Otherwise it will run forever and your program will likely eventually run out of memory.

The For Loop

This one is a little more complicated. Let’s look at an example first:


// this will print out 0 1 2 3 4
for (var i = 0; i < 5; i++) {
  console.log(i);
}

In the first like of the for statement the different parts specify how the loop will work. In this example, the order of execution is as follows:

    1. First var i = 0 is run and i is initialized to zero
    2. Next, i < 5 is evaluated to see if the loop should break
    3. Then the code inside the loop is run (i.e. console.log(i))
    4. Then i++ is run which is the same thing as i = i + 1
    5. Finally, we go back to #2

Code Along

In the code along this week we are going to write some code for a multiply() function which uses addition with a loop to multiply.

Categories: Tech Stuff

Jeff Whelpley

CTO at GetHuman, Google Developer Expert, AI and Angular Boston meetup organizer

Leave a Reply

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