JavaScript

Learning JavaScript: For loops

Learning JavaScript: For loops

Continuing on my mission to learn JavaScript, next I’m going to look at for loops to find out what they do and how they work.

Please note: This article is subject to constantly change as and when I learn more!

What is a ‘for loop’?

A ‘for loop’ is a statement which allows a block of code to be run over and over again with different values each time. This is what the bare bones look like:

// Create the for loop
for (statement1; statement2; statement3) {
	// Code that the for loop runs goes here...
}

How it works

First of all, the for loop is defined and three statements are separated by semicolons ; and surrounded by parentheses ( ). These statements will control how the loop runs/if it even runs at all, and are explained as follows:

  • The first statement is executed before the loop is run;
  • The second statement defines a condition that must be met before the loop can start running;
  • The third statement is executed after the loop has been run.

Then the code that is to be executed each time the loop runs is placed within the curly brackets { }. See the example below for a simple way that a for loop can be used…

Simple example: For loop that counts upwards

This example will act as a counter to print the numbers 1 to 10 in succession. See the explanation below the code snippet to see how it works.

The markup

JavaScript

// Create the for loop
for (var i = 1; i <= 10; i ++) {
	// Print out the value of i each time the loop runs
	console.log(i);
}

Result of the loop

1
2
3
4
5
6
7
8
9
10

Code explanation

  1. On line 2, the for loop is defined and followed by three statements separated by semicolons ; and contained within parentheses ( ):
    • The first statement is what happens before the loop is run. A new variable called i is created and is given an initial value of 1;
    • The second statement states the condition that must be met before the loop is run. The variable name (i) is followed by <= 10; this means that the loop will run as long as the variable value is less than or equal to 10;
    • The third statement is what happens after the loop is run. The variable value is increased by 1 each time the loop is run.
  2. Line 3 is what the loop does when it is run. In this case, the variable value is printed;

So basically, each time the loop runs, a number is printed out until the conditions for the loop to run are no longer met, and it stops.

Explaining how it works in simpler (and longer winded) terms:

This is a bit long winded, but it goes through exactly what steps the loop undertakes when it is executed:

  1. The variable value starts off at 1;
  2. The value is checked to see if it is less than or equal to 10 which it is, so the loop runs;
  3. The value of 1 is printed;
  4. The value is increased by 1 (so now it’s 2);
  5. The new value of 2 is checked to see if it is less than or equal to 10 which it is, so the loop runs;
  6. The new value of 2 is printed;
  7. The value is increased by 1 (so now it’s 3);
  8. These steps run over and over again until the variable value reaches 10;
  9. The new value of 10 is checked to see if it is less than or equal to 10 which it is, so the loop runs;
  10. The value of 10 is printed;
  11. The value is increased by 1 (so now it’s 11);
  12. The new value of 11 is checked to see if it is less than or equal to 10 which it is not, so the loop stops.

Increments and decrements

In my counter example, I used ++ in the last statement to increase the value each time, but I could have used any of the following instead to make the counter behave differently:

  • ++ increments the value by 1 each time
  • -- decrements the value by 1 each time
  • +=3 increments the value by 3 (this can be any number) each time
  • -=3 decrements the value by 3 (this can be any number) each time
  • *=3 increments the value by itself multiplied by 3 (this can be any number) each time
  • /=3 decrements the value by itself divided by 3 (this can be any number) each time

Decrement counter example

In this example, I’m going to create a counter which will work in the opposite direction to my other example; it will count backwards from 10 to 1.

The markup

JavaScript

// Create the for loop
for (var i = 10; i >= 1; i --) {
	// Print out the value of i each time the loop runs
	console.log(i);
}

Result of the loop

10
9
8
7
6
5
4
3
2
1

To make this work, the initial value is set to 10 and the second statement needs to tell the counter to count downwards until it gets to 1, so i >= 1 is placed here. For the third statement, I want the counter to decrement by 1 each time, so -- is used.

In a future post, I will be looking at how for loops and arrays can work together.

if/else statement within a for loop

If/else statements allow an action to be carried out if a particular condition is matched, else a different action will be carried out. So if an if/else statement is placed within a loop, it’ll run each time the loop does.

The example below shows how the numbers printed from a counter for loop can be manipulated. I want the loop to tell me which numbers are odd and which are even; if the number is even, I want (even) to be printed after the number and if it is odd, I want (odd) to be printed.

Here is the code that can accomplish this and the result – the loop is counting from 1 to 10 and checking each time it is run to see if the variable value passed in is divisible by 2 (if it is, it is an even number). The code will be properly explained after the markup:

JavaScript

// Create the for loop
for (var i = 1; i <= 10; i ++) {
	// If the number is even, print '(even)' after the number
	if (i % 2 === 0) {
		console.log(i + "(even)");
	}
	// Otherwise, print '(odd)' after the number
	else {
  		console.log(i + "(odd)");
	}
}

Result of the loop

1(odd)
2(even)
3(odd)
4(even)
5(odd)
6(even)
7(odd)
8(even)
9(odd)
10(even)

Code explanation

  1. On line 2, the for loop is created and the variable i is given an initial value of 1, the loop will stop at 10 and will increment by 1 each time the loop runs (the loop will count from 1 to 10);
  2. Line 4 starts the if/else statement. Within the parentheses ( ), I am stating the condition that “if the value of the i variable is divided by 2 and it has a remainder of 0, do the action in the curly brackets which follow” (if a number has a remainder of 0, that means that the number is even);
  3. On line 5 within the curly brackets { }, the console is instructed to print the value of i followed by the string "(even)";
  4. On line 8, the else statement starts. Anything within the curly brackets { } following this will apply to values which do have a remainder when divided by 2 (the odd numbers);
  5. On line 9 within the curly brackets { }, the console is instructed to print the value of i followed by the string "(odd)".

Nested for loops

For loops can also be nested inside of each other. In my simple example below, imagine that I want to print out a list that I can record my workouts on in the gym. I want to do four exercises with three sets each, so I’ll need a list that will reflect this.

I can use a for loop nested within a for loop to achieve this. I’ll need the first loop to run four times, and each time it runs, to print out an exercise number. The loop within it will run three times to create the required number of sets within each exercise I want to complete so I can tick them off as I do them.

JavaScript

// Create the first for loop
for (var i = 1; i <= 4; i ++) {
	console.log("Exercise " + i + ":");
	// Create the second for loop
	for (var j = 1; j <= 3; j ++) {
		console.log("Set " + j);
	}
}

Result of the loop

Exercise 1:
Set 1
Set 2
Set 3
Exercise 2:
Set 1
Set 2
Set 3
Exercise 3:
Set 1
Set 2
Set 3
Exercise 4:
Set 1
Set 2
Set 3

For loop within a function

A for loop can be placed inside a function. This way, parameters can be passed into the function to be used in the loop.

I am going to illustrate this by creating a loop within a function which will print times tables of any number from 1x to 5x. In this case it will print the 12 times table. The explanation of how it works is provided below the code snippet.

JavaScript

// Create the function
var timesTable = function(number) {
	// Create the for loop
	for (var i = 1; i <= 5; i ++) {
		var answer = number * i;
		console.log(number + " times " + i + " equals " + answer);
	}
};

timesTable(12);

Result

12 times 1 equals 12
12 times 2 equals 24
12 times 3 equals 36
12 times 4 equals 48
12 times 5 equals 60

Code explanation

  1. On line 2, the variable timesTable is defined as a function with the parameter name number within the parentheses ( );
  2. On line 4, a for loop is started which will have the variable value of i increment each time the loop is run, starting at 1 and ending at 5 (meaning the loop will run 5 times);
  3. Line 5 is what will happen each time the loop is run. A variable called answer is created which will store the result of the argument passed into the function when it is called, multiplied by the value of i;
  4. Line 6 also happens each time the loop is run. Each time the loop is run, “# times # equals #” will be printed:
    • The first # being the argument passed in from the function call;
    • The second # being the incremental loop number (i);
    • The third # being the value of the variable answer I just created.
  5. On line 10, the function is called, passing in the argument 12 to create the 12 times table. Whichever number is passed in here determines what times table will be printed by the function.

For loop using an array

An array stores multiple pieces of data at the same time (see my post on it for a more in depth explanation). A for loop can be used to access every item in an array one by one.

My example below shows how I can print out a list of every flavour cake that I like. I use an array to store the cake flavours for later use. Each time the loop runs, it looks at each array item in turn and prints out “I like *arrayitem* cake“. See the explanation below the code snippet to see how it works.

JavaScript

// Create the array
var flavours = ["chocolate", "ginger", "carrot", "coffee", "walnut", "banana"];

// Create the for loop
for (var i = 0; i < flavours.length; i ++) {
	console.log("I like " + flavours[i] + " cake");
}

Result

I like chocolate cake
I like ginger cake
I like carrot cake
I like coffee cake
I like walnut cake
I like banana cake

Code explanation

  1. On line 2, the variable flavours is created as an array and within the square brackets [ ], all my flavours are added as strings ("chocolate", "ginger", "carrot", "coffee", "walnut" and "banana");
  2. On line 5, a for loop is started:
    • The first statement sets the variable value of i to start at 0. This will mean that it starts at the first item of the array. Arrays use zero-based indexing so the first item ("chocolate") will be set at this position;
    • The second statement is i < flavours.length, which means that the loop will run until it reaches the end of the flavours array. < is used because the length of the array is 6 (it contains 6 items) but because arrays use zero-based indexing and the first item has an index of 0, the last item in the array will have an index number of 5 (I personally find this confusing);
    • The third statement i ++ means that the value of i will be incremented each time the loop is run, which in this case means that each item in the array will be cycled through in turn.
  3. Line 6 will happen each time the loop is run. A phrase is printed to the console saying “I like *flavour* cake“. flavours[i] is used to insert the array item into the phrase – this means that it looks at the flavours array and picks out the value of i at that particular time (so for example on the 4th run of the loop, the value of i would be 3 – this means that the array item coffee will be inserted).

For loop using an array within a function

This example is very similar to the one above, so the way the loop is interacting with the array is exactly the same. However, it is placed within a function and can be called as such, with arguments passed in. See the explanation below the code snippet for a full description of what the additional code is doing.

JavaScript

// Create the array
var flavours = ["chocolate", "ginger", "carrot", "coffee", "walnut", "banana"];

// Create the function
var cake = function(singleFlavour) {
	// Create the for loop
	for (var i = 0; i < flavours.length; i ++) {
		console.log("I like " + singleFlavour[i] + " cake");
	}
};

cake(flavours);

Result

I like chocolate cake
I like ginger cake
I like carrot cake
I like coffee cake
I like walnut cake
I like banana cake

Code explanation

  1. Line 2 creates the array with cake flavours as strings within it;
  2. Line 5 starts the cake function which contains the loop, and it takes one parameter – singleFlavour;
  3. Lines 7-9 contain the loop which cycles through the array:
    • On line 8, this is what the loop with do each time it is run – which is to print the phrase “I like *flavour* cake“. Here, instead of passing in the array name flavours as I did in the previous example to directly loop through the array, I have passed in the parameter name singleFlavour. Therefore, it will take in any data that is passed through as an argument when the function cake is called and attempt to loop through it.
  4. On line 12 the cake function is called and the argument flavours is passed in within the parentheses ( ), which means the flavours array will be passed in and used within the function, creating the result shown when the code is run.