Skip to content

Grammar

4. The grammar:

A. Conditional

The order in which the instructions of a program are executed, by default, sequential, executing instruction after instruction. Thus a program will be written as a succession of instructions or sentences, using a point and comma to indicate the end of the instruction.

A series of statements can be grouped into a block by locating them between keys. Sometimes it is necessary to alter this order for this, the control instructions are used: conditional, selection and loops. They will be the conditional sentences the first we will see.

A conditional statement is an instruction in which a comparison is made and according to the true or false result (true or false) of the same the program will continue to run one or other instructions.

The simplest conditional that we can write is one that executes U omits a series of statements depending on whether the check gives true or false. The syntax of this sentence is.

if (condition) {block to execute if the condition is true}
else
{block to execute if the condition is false}

If we omit the part of else we will have a simple conditional. This syntax in some cases can be simplified using the following form:

(condition)? {block if certain} : {Block if false}

In the following example, we avoid a division by zero

if (div == 0)
logger.warn('It can not be divided by 0');
else
coc = num / div;

Another example using the second form:

str = (num >= 0)? '+' : '-';

In this example str will take the value + If num is positive or zero and - if it is negative.

The sentences if can be nestled, that is, within an IF statement, more sentences if can be put up. Conditions can be simple as in these examples or can be linked using operators && and || (and and or logical). Let's see an example in which we check if a number is between 1 and 5:

if (num>=1) && (num < 5) {
list[index] = 'Very low';
lows++;
}
index++;

In this example if num is between 1 and 5 (excluding) is recorded in a list 'very low' words and increases the variable low. As we see the part of else has not been used and as more than one judgment must be executed, we have enclosed them between keys. If num does not meet the condition, this block is skipped. In any case the following instruction that is executed after the conditional will be the one that increases the value of Index.

B. Multiple choice

The conditional structure allowed the most to choose between two possible paths in the execution of a program: if the condition was a block, another block is executed.

But there may be cases in which the program must have more than two alternatives, for example if we want a program that presents a title in a four possible language. This can be solved by various if nested, following the example we have to choose between languages: Spanish, English, French and German.

if (idiom == 'spanish') {
  SendSpa();
} else if (idiom == 'English') {
  SendEng(); 
} else if (idiom == 'French') {
  SendFre();
} else if (idiom == 'German') {
  SendGer();
} else {
  error('Non-present language');
}

As we see, it is a quite complex code. For these cases we have the statement switch ... case ... default, multiple selection. The previous example would be:

switch (idiom) {
  case 'spanish':
    SendSpa();
    break;
  case 'english':
    SendEng();
    break;
  case 'french': 
    SendFre(); 
    break;
  case 'german': 
    SendGer();
    break;
  default:
    error('Non-present language');
}

During the execution, the variable language is compared with each of the possible values and when they coincide, execute the corresponding code. The instruction break puts an end to the block and makes the program jump to the instruction following the swith() statement, if the program is omitted, it would continue with the following comparison. The section of default is optional, its purpose is to execute some code when none of the conditions is met.

C. Loops

Sometimes it is necessary to repeat the same set of sentences several times. For example, to erase all the elements of an array, we must simply make delete in each of them, it is a sentence that will be repeated as many times as long as the array is. This is a typical work for repetitive structures or loops. In essence, the execution of a loop is to execute repeatedly the same part of the program (body of the loop) until a certain condition is met, in which case the repetition is over and the program continues with its normal flow. There are several loop statements: while (Condition) {...}, do {... Condition) and for (Counter; Condition; ModCont ) {... ...

While sentence

In this structure, the program first checks the condition: if it is true, it is going to execute the body of the loop, and if it is false, it happens to the instruction next to the While statement. As always, an example will clarify everything:

let list = new Array(10);
let ind = 0;
while (ind < 10) {
  list[ind] = '0';
  ind++;
}

In this example, while the value stored in ind is less than 10 (the length of the array) will be stored in each element of the array list a 0 and increasing the value of ind. When this value is 10 the program will not enter the body of the loop. If the value of ind is not increased, the loop would never end, the program would indefinitely run the body of the loop.

Do...while sentence

It is a loop in which the condition is checked after the first iteration, that is, the body of the loop is executed at least once. The previous example would be as follows:

let list = new Array(10);
let ind = 0;
do {
  list[ind] = '0';
  ind++;
} while (ind < 10)

As we see here, the keys are essential to enclose the body of the loop. It is not contemplated at the Standard ECMA 1.5.

Sentencia for

This statement uses a control variable as a counter to control the repetition of the loop body. The statement gives an initial value to this counter and in each iteration it modifies it as indicated and checks the condition, if the loop body is executed, if it does not jump and continues by the following statement. We see the previous example using this sentence:

let list = new Array(10);
for (let ind = 0; ind < 10; ind++) {
  list[ind] = '0';
}

As we see the body of the loop does not increase the variable ind , this is indicated in the head of the sentence. This code does exactly the same as the previous one.

For ... in sentence

It is a variant of the sentence for used to iterate or travel all the elements of an object or an array. Use a control variable that in each iteration takes the value of the element of the travel object. For example, if you test this code you can see all the elements of the document Document:

for (let item in document) {
  logger.warn(item);
}

With a matrix the control variable takes the value of the indexes of the matrix, not its content.

D. Loops break

Although we try to use a structure programming, it may ever be necessary to interrupt the repetition of a loop or force an iteration from it, this can be achieved through the sentences break and continue. They are sentences applicable to any of the loop structures in JavaScript.

break

The Break statement interrupts the current iteration and sends the program to the instruction that follows the loop.

let list = new Array ('a','b','c','z','x','f');
let item ;
for (item in list) {
  if (list[item] == 'z') {
    break;
  }
  logger.warn(list[item]);
}

This example would write the content of the array list until you find a letter z.

continue

The sentence continue interrupts the current iteration and sends the program to check the condition, if this is true continues with the next iteration.

let list = new Array ('a','b','c','z','x','f');
let item ;
for (item in lista) {
  if (list[item] == 'z') {
    continue;
  }
  logger.warn(lista[item]);
}

This example would write the content of the array by jumping the letter z.