C-like control structures of the JavaScript language

The JavaScript loops and conditions are those of the C language but extended and with greater flexibility. For example, switch case accepts any type of value.

if else
for
for in
while
break and continue
do while
switch case

if ... else

The syntax for conditional execution of code is:

if(condition) { } 

or

if(condition) { } else { }; 

Curly braces are optional if there is a single instruction while parentheses are always required.
When the evaluation of the condition returns true, the instructions are executed otherwise it is the else part when it is present.

Example:

if(a == 5)
{
    document.write("a is 5");
}

It would be possible as in C to assign a variable inside the condition, a practice that should be avoided.

for

To run a series of instruction in a loop, the syntax is:

for(var = initializer; condition; increment)
{
 ...instructions...
}

Example:

for(var i = 0; i < 10; i++)
{
    document.write(i + "<br>");
}

This is the basic formulation. It is also the fastest, as shown by  benchmarks on various loops in JavaScript.
But there are other formulations, easier to write.

for in

This structure allows parsing the contents of an object to access the list of its properties and their values. If it is an array, the properties are the indices of the array.

Syntax:

var arr = ["a", "b", "c"];
for (x in arr)
{
  document.write(arr[x]);
}

Here are some examples of for in control use...

1) for in with an array

for in assigns the indices of the array to a variable, and this variable is used to retrieve the contents of the array.

var a = new Array("one","two","three","four","five");
a[5]="six";
for(x in a)
{
   document.write(x + ") " + a[x] +  "<br>");
}
  

2) for in with an object

The for in structure assigns the name of the properties of the object to a variable that is used in turn to retrieve the values of the properties.

function car()
{
 this.passengers = 5;
 this.speed = 250;
 this.wheel = 4;
 this.cost = 10000;
}
var v = new car();
for (x in v)
{
   document.write(x + ":" + v[x] + "<br>");
}

Another example, for in inside a function with an object...

function scanObject(obj, name)
{ 	
  var str = ""; 	
  for(i in obj)  	
  {
       str += name + "." + i + " = " + obj[i] + "<br>"; 
  }
  return str; 
}
v = new car(); 
v.cost = 5000;  
document.write(scanObject(v, "car")); 

3) for each (no standard)

For each gives directly the content of the object and works as the foreach PHP control. This structure has been added to JavaScript 1.6.

Syntax with the same array still:

for each(x in arr)
{
   document.write(x);
}

while

For a loop running as a given condition is true, implying that the conditional expression contains a variable that is modified in the body of the loop.

while(condition) { }

Example:

var i = 0;
while(i < 3)
{
   document.write(arr[i]);
   i++;
}

It is easy to forget to increment the variable of the condition, which causes an infinite loop and frozes the browser. To be used therefore with cautious. The for loop of the following example will have the same result and is therefore preferable, as is for in:

for(i = 0; i < 3; i++)
{
    document.write(arr[i]);
}

break and continue

The break instruction can exit the loop, while continue moves to the next iteration.
In the example, is created an endless loop with a condition "true" that will be always true of course, and it relies on the break command to end the loop:

var arr = ["a", "b", "c", "d", "e"];
var x = 0;
while(true)
{
  if (x == 2) { x++;  continue; }
  if (x == arr.length) break;
  document.write(arr[x]);
  x++;
}

The "c" string is not displayed because the loop continues when the index reaches 2.
The loop stops when the size of the table is reached, thanks to the break instruction.

If a while control can easily turn into an infinite loop, things get even worse with the use of the continues command as it can bypass the instruction to increment the variable of the condition and also skip the break instruction.

The ability to associate a label still does not help us to avoid this problem because the label must be declared prior to use continue.

label:
...instructions...
continue label;
  
What makes this option of little interest.

do ... while

do while is similar to the while structure with the condition postponed to end of the loop.
The content of the loop will always be executed at least once.

do { } while(condition)

Example:

var i = 0;
do
{
  document.write(arr[i]);
  i++;
} while(i < 3);

In this case, there is no difference with while. The difference appears only if the condition is never met. For example (i> 4) does nothing with while and displays "a" with do while.

switch case

Executes a processing to be choosen depending on the value of a conditional expression.

Syntax:

switch(expression)
{
  case value:
      ... instructions ...
      break;
  case value:
      ...instructions...
      break;
  default:
  ....
}

The cases are compared in turn and the first value that corresponds to the expression is retained, and the associated code is executed. The break instruction marks the end of code for the case, so if break is omitted, the code of the following case is executed in turn. And the reserved word default enables an emergency procedure when no event is verified.

Variables and expressions may be assigned to the cases, example:

var x = 10;
var y = 8;
switch(x)
{
case 5: break;
case y + 2:
document.write("x = y + 2");
break;
default:
document.write("Unknown");
}

Conclusion

JavaScript inherits the unsafe syntax and structures of the C language, which includes the aberration of the assignment within a condition, with effects amplified in a client-server environment. We must be attentive to possible infinite loops and prefer for performances to use for and for .. in.
But it offers a greater freedom thanks to its dynamic nature.

© 2008-2022 Xul.fr