Loops in javascript are something very useful and which are used all the time. They're not specific just for javascript, rather they can be found in almost all programming languages in the world. Loops are one of the most fundamental building blocks in programming, and some argument that all you really need to create a program are only three things. Sequences (statements), selections (if and else) and iterations (loops).

What a loop is

A loop is exactly what it sounds like, something repetitive that does things over and over again. If one in javascript would like to for example write "i like apples" 10 times in a row, you could of course just write 10 lines saying just that. Or you could use a loop. The advantage with a loop is that then you'll only have to type the string once, and have javascript repeat the output for you.

The real usage of loops are of course not to just output the same text 10 times in a row, instead they're many times used to print out things that are dynamic. Like for example all rows from a database table. After reading this article you've hopefully understood and learned the real power of loops.

The while loop

var num = 0;

while (num < 10) {
console.log('The num is: ' + num);
num++;
}

The while loop in javascript is the most simple to learn and understand so we'll start with that. What it does is it takes an expression as parameter and executes the code inside its curly braces over and over again until the expression is fulfilled. In the example above the text will be printed out 10 times and then the loop is terminated. This is because the variable num which initially has the number 0 gets incremented by 1 every loop, and eventually reaches 10 where the expression results in false and terminates. The while loop will continue to loop as long as the expression results in true.

// Loops through a string and prints all letters each

var num = 0;
var str = 'Hello, World!';

while (num < str.length) {
console.log(str[num]);
num++;
}

In javascript it's also possible to loop through strings. There's already many built in methods for working with them in different ways. But to for example just print out every single character of a string it could be done as in the example above. All strings have a property called "length" which contains a number of how many characters are in them, so we can easily use that as a condition for when the loop should finish.

For

for (var i = 0; i < 15; i++) {
console.log('The num is:' + i);
}

For and while are actually two very similar loops. They both repeat something until their expression has been fulfilled, and just have different syntaxes. What differs them is that in the for loop a variable is declared and its condition and incrementation are set in the first line, instead of all over the place like in the while loop.

Usually the for loop is used when you already know from the start how long it's going to iterate, for example when looping through an array with an already known length. And while is when you don't know, like when the expression is something else than just "less than a number" for example.

Do while

var num = 0;

do {
console.log('The num is:' + num);
num++;
}
while (num < 5);

If you now understand how the while loop works do while will be easy to learn. It's very much like the ordinary while except for one difference. That is in what order it evaluates the expression. While evaluates the expression first and then executes the code inside the block, do while executes the code first and then evaluates the expression. So what it does is that it guarantees the code inside the curly braces will be run at least once, even if the expression results in false directly.

For in

var fruit = {
type: 'banana',
color: 'yellow',
poisonous: 'no'
};

for (var property in fruit) {
console.log(property + ': ' + fruit[property]);
}

The loop for in is a special loop in javascript, and the first thing people who know other programming languages might think is that it's equivalent to a "foreach loop". That's however not true because the for in is initially meant to loop through objects. It can of course be used to loop through strings, arrays etc. But because the way it's implemented it can never guarantee it will loop though them in the correct order. For those cases it's better to use a normal while or for loop.

What an object is will be explained in a later chapter. But for in is perfect for looping through their properties, and will simply just loop through them all one by one. To get the objects values in the loop it can be done as in the code example above.

Break & continue

Break and continue are fairly easy to use, so we'll just keep this simple and not overcomplicate things.

var str = 'The loop breaks at &-signs';
var newStr = '';

for (var i = 0; i < str.length; i++) {
newStr += str[i];

if (str[i] === '&') {
break;
}
}
console.log(newStr); // The loop breaks at &

What break does is it simply just breaks a loop or "finishes" is. When a break statement is encountered in a loop it immediately terminates and javascript continues on doing other things in the script. Some think break is a bit "ugly" to use in loops, but it has its use cases and in switch statements it's a must.

var str = '#Hashes #are #removed #from #the #string';
var newStr = '';

for (var i = 0; i < str.length; i++) {
if (str[i] === '#') {
continue;
}
newStr += str[i];
}
console.log(newStr); // Hashes are removed from the string

Continue doesn't terminate the loop like break does but instead just jumps over the current "loop round" and continues with the next round. It basically says: this round is finished, jump back to the top.

Some more reading about loops in general if wanted can be found at wikipedia.org/wiki/Control_flow#Loops

Try it yourself

  1. Set a variable to 0, increment it to 10 and print it out with the different loops while, do while, for, and for in.
  2. Use a break statement to stop a loop at the number 5.