Science Library - free educational site

Loops and conditionals (JS)

As in all programming languages, JavaScript allows processes to be repeated as many times as required. The loops are controlled by conditions. These may be simple counters (do this x times then go on to the next bit), or run if or until certain conditions are met.

In programming it is very common that a list of elements needs to be iterated (repeatedly called).

In JavaScript, this is simply achieved using Array (which have only numerical indices in JavaScript) - just use the classic loop:

abc = ['a', 'b', 'c']

for (var i = 0; i < abc.length; i++) {
console.log(abc[i]);
}

There is only one problem with this example: every time the list abc is called it needs to be recalculated.

In many cases, this makes no difference. However, if the list is sizeable, this could lead to appreciable delays.

It is therefore a good practice to avoid this inconvenience - and this is not hard to do: simply store the length of the list prior to starting the loop:

abc = ['a', 'b', 'c']

var l = abc.length;
for (var i = 0; i < l; i++) {
console.log(abc[i]);
}

An even 'cleaner' method is to utilise the native method forEach() for arrays in JavaScript:

abc = ['a', 'b', 'c']

abc.forEach(function(value, index, array) {
console.log(value);
});

The disadvantage of this method is that it relies on a relatively new JavaScript version (ECMAScript 5), and therefore is not supported by some browsers (such as IE < 9). We need to allow for this shortfall - see Mozilla Developer article for more specific information.

So far, so good. But... what if we wish to iterate an associative list? Note: JavaScript does not have associative arrays (as, for example, does PHP), but it is possible to use normal objects in an analogous manner.

It might seem obvious to use a for... in loop?

var o = {
  • 'one': 'I',
  • 'two': 'II',
  • 'three': 'III',
  • 'four': 'IV',
  • 'five': 'V'
};

for (k in o) {
console.log(k, " = ", o[k]);
}

However, this would be committing a serious error. The for... in loop does not iterate only the properties of an abject, but also all of its numeratable properties - that is, also those inherited from the prototype.

We must therefore ensure that the properties passed to the loop do not originate from the prototype. For this purpose, we use the hasOwnProperty method:

var o = {
  • 'one': 'I',
  • 'two': 'II',
  • 'three': 'III',
  • 'four': 'IV',
  • 'five': 'V'
};

for (k in o) {
if (o.hasOwnProperty(k)) {
console.log(k, " = ", o[k]);
}
}


if ... else

The if statement is probably the one you will use the most in any programme. A flowchart is a good way to design the logic of a programme, and questions boxes (e.g. is user male?) will usually have two possible answers (i.e. binary): yes or no. This works well with a loop with a binary conditional:

if(x >= 100) {

document.write('The price €' . x . ' is beyond my means');

}

else if(x >= 50 && x <= 99.99){

document.write('The price €' . x . ' is standard');

}

else {

document.write('Get them while they are hot!');

}

Where there are more than one possible condition sets, the elseif....else series can direct the run through the appropriate script.

Switch

Using switch (JS), if the number of condition matches exceeds 3, the switch function provides an alternative to the elseif....else. elseif....else will continue to work for any number of condition sets, but it begins to become a little cumbersome. If nothing else, switch is a lot easier to read for multiple possible conditions.

switch allows for a non-match of conditions, with a default. break instructs the programme to exit the switch function after completing the code which satisfies the set conditions(s).

switch(true) {

case (x >= 100):

document.write('The price €' + x + ' is beyond my means');

break

case (x <= 99.99 && x > 50):

document.write('The price €' + x + ' is standard');

break

default:

document.write('Get them while they are hot!');

}

The order of condition statements means that the switch function will break after the first condition to be found true. In the following example, the hour of day is assigned to variable h, which is then tested against a sequence of conditions in a switch construct. Since the conditions of 14, 15, 16 are tested prior to < 18, if the time is mid-afternoon the message "Good mid-afternoon person" will be returned instead of "Good afternoon person". Similarly, there is no need to specify afternoon as between 12 and 18, since the morning test is made before the afternoon test.

<p id="demo"></p>

<script>

var message;

var d = new Date();

var h = d.getHours();

switch (true) {

case (h < 12) :

message = "Good morning person";

break;

case (h == 14):

case (h == 15):

case (h == 16):

message = "Good mid-afternoon person";

break;

case (h < 18) :

message = "Good afternoon person";

break;

default:

message = "Good evening person";

}

document.getElementById("demo").innerHTML = message;

<script>

Ternary Operator

The ternary operator (?) is a very useful shorthand for the yes/no question. e.g. If the person is male (i.e. returned by a radio button in a form), use 'Mr' salutation, otherwise 'Mrs.'.

gender = 'F';
gender == 'M'? a = "Mr." : a = "Mrs."
document.write("Dear " + a + " Smith")

This is superbly useful in tables, where every second row can be styled a different colour. Is current class white? If yes, make class grey, otherwise white.

bg_color = "#fff";
bg_color == "#fff"? bg_color = "#ccc" : bg_color = "#fff"

Loops

Using a conditional statement, loops can run a sequence as many times as required, and break when the condition is met. Loops can be of different types: while, do..while, and for.

while

The loop is run if the preset condition is true. While x is less than y, do z, otherwise pass on to the next part of the script.

counter = 0;
while (counter < 10) {
counter ++;
counter == 1 ? s = "" : s = "s";

document.write("We have done this loop so far: " + counter + " time" + s + "<br />");

}

do..while

This loop is run until the post-set condition is true. Do z, then check if x is less than y. If not, do z again, otherwise pass on to the next part of the script.

counter = 1;
do {
counter == 1 ? s = "" : s = "s";

document.write("We have done this loop so far: " + counter + " time" + s + "<br />");

} while (++counter <= 10)

Note the changes required to the initial value of the counter, and the condition to be checked, since the counter is incremented after the first loop run.

for

A very common way of looping is to run the sequence for a set number of times. The difference to the while loop is the placing of the condition in the for statement, rather than in the body of the loop. Do z i number of times.

for (i = 1; i <= 10; i++) {
i == 1 ? s = "" : s = "s";

document.write("We have done this loop so far: " + i + " time" + s + "<br />");

}

Escaping Loops

In handling large amounts of data of a similar type, such as from a database, it may be useful to run a loop until a value is found, and then exit the loop.

document.write("What is the smallest integer whose cube is greater than half a million?<br />");

for (i = 1; i <= 10000; i++) {

cube = i * i * i;
if(cube > 500000) {

document.write("The cube of " + i + " = " + cube + " which is greater than 500,000<br />")

break } }

This operation could be executed by a while loop, but the for allows a maximum number of trials to be set ( i <= 10000), which prevents a logic error in the function sending the programme into an infinite loop, which you don't want, because it can cause all sorts of problems for servers and users.

An alternative to break is continue, which interrupts the loop for that iteration only.

document.write("What are all the integers whose cubes lie between 1001 and 2000?<br />");

for (i = 1; i <= 100; i++) {

cube = i * i * i;

if(cube <= 2000) {

if(cube <= 1000){ continue }

document.write("The cube of " + i + " = " + cube + ", which is between 1001 and 2000<br />")

}

Content © Renewable-Media.com. All rights reserved. Created : June 3, 2014 Last updated :March 11, 2016

Latest Item on Science Library:

The most recent article is:

Trigonometry

View this item in the topic:

Vectors and Trigonometry

and many more articles in the subject:

Subject of the Week

Universe

'Universe' on ScienceLibrary.info covers astronomy, cosmology, and space exploration. Learn Science with ScienceLibrary.info.

Science

Great Scientists

Werner Heisenberg

1901 - 1976

Werner Heisenberg was a German physicist, and a key member of the 'Copenhagen Interpretation', which proposed an observer-creation understanding of quantum phenomena, based on Niels Bohr's theories and Heisenberg's Uncertainty Principle.

Werner Heisenberg, 1901 - 1976. German physicist and proponent of the Heisenberg Uncertainty Principle.
Vitruvian Boy

Quote of the day...

The Stone Age also did not come to end because of a shortage of stones.

ZumGuy Internet Promotions

Umwelt.Science