JavaScript Course 3: Control Flow

From WikiMLT

Ref­er­ences

Con­di­tion­al state­ments

In JavaScript we have two types of con­di­tion­al state­ments:

  • If..else
  • Switch..case

The syn­tax con­ven­tion is to put the open curly brace '{' at the same line as the con­di­tion.

If..else

if con­di­tion with sin­gle and mul­ti­ple state­ments.

if (condition) statement;
if (condition) 
    statement;
if (condition) {
    statement_1;
    statement_2;
}

else if con­di­tion with sin­gle and mul­ti­ple state­ments.

if (condition_1) statement_1;
else if (condition_2) statement_2;
if (condition_1) {
    statement_1;
}
else if (condition_2) 
    statement_2;
if (condition_1) {
    statement_1;
} else if (condition_2) {
    statement_2;
    statement_3;
}

else if none of the con­di­tions is eval­u­at­ed to true.

if (condition_1) {
    statement_1;
}
else if (condition_2) {
    statement_2;
}
else {
    statement_3;
}

Full ex­am­ple:

// If hour is between 6am and 12pm: Good morning
// If hour is between 12pm and 6pm: Good afternoon
// Otherwise: Goog evening
let hour = 10;

if (hour >= 6 && hour < 12) {
    console.log('Good morning');
}
else if (hour >= 12 && hour < 18) {
    console.log('Good afternoon');
}
else {
    console.log('Good evening');
}

Switch..case

With Switch..case we can com­pare a val­ue of a vari­able against a bunch of val­ues. Ba­sic struc­ture:

let variable = 'value';
switch (variable) {
    case 'value_1':
        console.log('actions for value_1');
        break;
        
    case 'value_2':
        console.log('actions for value_2');
        break;
        
    default:
        console.log('default actions');
}

Im­ple­men­ta­tion of If..else for the same task, which looks bet­ter, tidy and sim­ple.

if (varuable == 'value_1') console.log('actions for value_1');
else if (varuable == 'value_2') console.log('actions for value_2');
else console.log('default actions');

Loops

The dif­fer­ent loops in JavaScript serves for re­peat­ing an ac­tion num­ber of times. These are:

  • For loop – re­peats an ac­tion num­ber of times.
  • While loop – re­peats an ac­tion num­ber of times.
  • Do..while loop – re­peats an ac­tion num­ber of times.
  • For..in loop – it­er­ates over the Prop­er­ties of an Ob­ject or over the El­e­ments or Items in an Ar­ray.
  • For..of loop – it­er­ates over the El­e­ments or Items in an Ar­ray.

For loop

The for loops re­peat an ac­tion num­ber of times, it con­sists of three state­ments.

for (initial_expression; condition; increment_expression)
    console.log('action to repeat');
  • With­in the initial_​​​expression we de­clare and ini­tial­ize a vari­able, usu­al­ly the vari­able is named i which is short­cut from in­dex and it is com­mon con­ven­tion of for loops: let i = 0 – this is what we called the loop vari­able.
  • With­in the con­di­tion we com­pare the val­ue of the loop vari­able [i] with some­thing else. The loop will run as longer its con­di­tion eval­u­ates to true. For ex­am­ple, if you run the loop 5 times the con­di­tion should be: i < 5.
  • With­in the increment_​​​expression we de­fine the rule of the loop vari­able [i] in­cre­men­ta­tion, for ex­am­ple: i++.

Com­plete ex­am­ple:

for (let i = 0; i < 5; i++) {
    console.log('Hello world!');
    console.log('Repeat: ' + (i + 1));
}

Dis­play on­ly odd num­bers be­tween 1 to 5 (and in re­verse or­der):

for (let i = 1; i <= 5; i++) if (i % 2 !== 0) console.log(i);
for (let i = 5; i >= 1; i--) if (i % 2 !== 0) console.log(i);

While loop

While loops al­so re­peat an ac­tion num­ber of times. One key dif­fer­ence be­tween for loops and while loops is that with­in the for loops the loop vari­able is part of the loop it­self. In while loops you have to de­clare this vari­able ex­ter­nal­ly.

let i = 0;            // initial_expressio
while (i <= 5) {      // condition
    console.log(i);
    i++;              // increment_expression
}

Do..while loop

Do..while loops al­so re­peat an ac­tion num­ber of times. They are very sim­i­lar to while loops but they slight­ly dif­fer­ent. Do..while loops al­ways will be ex­e­cut­ed at least once, be­cause the the con­di­tion is eval­u­at­ed at the end of the it­er­a­tion.

let i = 0;            // initial_expressio
do {                  
    console.log(i);
    i++;              // increment_expression
} while (i <= 5);     // condition

In­fi­nite loops

We must avoid such sit­u­a­tion that leads to brows­er crash, etc. Such neg­a­tive ef­fect could be achieved with all kind of loops in JavaScript that re­peat an ac­tion num­ber of times.

let i = 0;              
while (i <= 5) {
    console.log(i);
    // i++;             // in this case 'i' will still '0' forever
}
do {
    // do something...
} while (true);

For..in loop

For..in loops it­er­ate over the Prop­er­ties of an Ob­ject.

const demoObject = {
    property_1: "value_1",
    property_2: "value_2",
};
for (let key in demoObject)
    console.log(key, demoObject[key]);
property_1 value_1
property_2 value_2

For..in could be used to it­er­ate over the El­e­ments or Items in an Ar­ray, but for..of loops are bet­ter for this pur­pose.

const demoArray = ['value_1', 'value_2', 'value_3'];
for (let index in demoArray)
    console.log(index, demoArray[index]);
0 value_1
1 value_2
2 value_3

For..of loop

For..of loops are ide­al way in or­der to it­er­ate over Ar­ray El­e­ments or Items. These loops work with the val­ues of the Ar­ray el­e­ments and we do not to deal with the ar­ray in­dex. It is avail­able in ES6 and lat­er.

const demoArray = ['value_1', 'value_2', 'value_3'];
for (let element of demoArray)
    console.log(element);
value_1
value_2
value_3

Break and Con­tin­ue

The key words break and con­tin­ue can change the be­hav­ior of all kind of loops in JavaScript. Here is an ex­am­ple with while loop:

let i = 0;
while (i <= 10) {
    if (i === 2) {i++; continue};
    console.log(i);
    if (i === 5) break;
    i++;
}
0
1
3
4
5