JavaScript Course 3: Control Flow: Difference between revisions

From WikiMLT
m (Стадий: 6 [Фаза:Утвърждаване, Статус:Утвърден]; Категория:JavaScript)
 
m (Text replacement - "mlw-continue" to "code-continue")
 
Line 17: Line 17:
=== If..else ===
=== If..else ===
<code>if</code> condition with single and multiple statements.
<code>if</code> condition with single and multiple statements.
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
if (condition) statement;
if (condition) statement;
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
if (condition)  
if (condition)  
     statement;
     statement;
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
if (condition) {
if (condition) {
     statement_1;
     statement_1;
Line 32: Line 32:


<code>else if</code> condition with single and multiple statements.
<code>else if</code> condition with single and multiple statements.
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
if (condition_1) statement_1;
if (condition_1) statement_1;
else if (condition_2) statement_2;
else if (condition_2) statement_2;
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
if (condition_1) {
if (condition_1) {
     statement_1;
     statement_1;
Line 43: Line 43:
     statement_2;
     statement_2;
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
if (condition_1) {
if (condition_1) {
     statement_1;
     statement_1;
Line 53: Line 53:


<code>else</code> if none of the conditions is evaluated to true.
<code>else</code> if none of the conditions is evaluated to true.
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
if (condition_1) {
if (condition_1) {
     statement_1;
     statement_1;
Line 66: Line 66:


Full example:
Full example:
<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
// If hour is between 6am and 12pm: Good morning
// If hour is between 6am and 12pm: Good morning
// If hour is between 12pm and 6pm: Good afternoon
// If hour is between 12pm and 6pm: Good afternoon
Line 84: Line 84:


=== Switch..case ===
=== Switch..case ===
With <code>Switch..case</code> we can compare a value of a variable against a bunch of values. Basic structure:<syntaxhighlight lang="javascript" class="mlw-continue">
With <code>Switch..case</code> we can compare a value of a variable against a bunch of values. Basic structure:<syntaxhighlight lang="javascript" class="code-continue">
let variable = 'value';
let variable = 'value';
</syntaxhighlight><syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue">
switch (variable) {
switch (variable) {
     case 'value_1':
     case 'value_1':
Line 99: Line 99:
         console.log('default actions');
         console.log('default actions');
}
}
</syntaxhighlight>Implementation of <code>If..else</code> for the same task, which looks better, tidy and simple.<syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight>Implementation of <code>If..else</code> for the same task, which looks better, tidy and simple.<syntaxhighlight lang="javascript" class="code-continue">
if (varuable == 'value_1') console.log('actions for value_1');
if (varuable == 'value_1') console.log('actions for value_1');
else if (varuable == 'value_2') console.log('actions for value_2');
else if (varuable == 'value_2') console.log('actions for value_2');
Line 114: Line 114:


=== For loop ===
=== For loop ===
The <code>for</code> loops repeat an action number of times, it consists of three statements.<syntaxhighlight lang="javascript" class="mlw-continue">
The <code>for</code> loops repeat an action number of times, it consists of three statements.<syntaxhighlight lang="javascript" class="code-continue">
for (initial_expression; condition; increment_expression)
for (initial_expression; condition; increment_expression)
     console.log('action to repeat');
     console.log('action to repeat');
Line 122: Line 122:
* Within the <code>'''condition'''</code> we compare the value of <u>the loop variable</u> [<code>i</code>] with something else. The loop will run as longer its <code>condition</code> evaluates to true. For example, if you run the loop 5 times the condition should be: <code>'''i < 5'''</code>.
* Within the <code>'''condition'''</code> we compare the value of <u>the loop variable</u> [<code>i</code>] with something else. The loop will run as longer its <code>condition</code> evaluates to true. For example, if you run the loop 5 times the condition should be: <code>'''i < 5'''</code>.
*Within the <code>'''increment_expression'''</code> we define the rule of <u>the loop variable</u> [<code>i</code>] incrementation, for example: <code>'''i++'''</code>.
*Within the <code>'''increment_expression'''</code> we define the rule of <u>the loop variable</u> [<code>i</code>] incrementation, for example: <code>'''i++'''</code>.
Complete example:<syntaxhighlight lang="javascript" class="mlw-continue">
Complete example:<syntaxhighlight lang="javascript" class="code-continue">
for (let i = 0; i < 5; i++) {
for (let i = 0; i < 5; i++) {
     console.log('Hello world!');
     console.log('Hello world!');
Line 129: Line 129:
</syntaxhighlight>
</syntaxhighlight>


Display only odd numbers between 1 to 5 (and in reverse order):<syntaxhighlight lang="javascript" class="mlw-continue">
Display only odd numbers between 1 to 5 (and in reverse order):<syntaxhighlight lang="javascript" class="code-continue">
for (let i = 1; i <= 5; i++) if (i % 2 !== 0) console.log(i);
for (let i = 1; i <= 5; i++) if (i % 2 !== 0) console.log(i);


</syntaxhighlight>
</syntaxhighlight>


<syntaxhighlight lang="javascript" class="mlw-continue">
<syntaxhighlight lang="javascript" class="code-continue">
for (let i = 5; i >= 1; i--) if (i % 2 !== 0) console.log(i);
for (let i = 5; i >= 1; i--) if (i % 2 !== 0) console.log(i);


Line 140: Line 140:


=== While loop ===
=== While loop ===
<code>While</code> loops also repeat an action number of times. One key difference between <code>for</code> loops and <code>while</code> loops is that within the <code>for</code> loops <u>the loop variable</u> is part of the loop itself. In <code>while</code> loops you have to declare this variable externally.<syntaxhighlight lang="javascript" class="mlw-continue">
<code>While</code> loops also repeat an action number of times. One key difference between <code>for</code> loops and <code>while</code> loops is that within the <code>for</code> loops <u>the loop variable</u> is part of the loop itself. In <code>while</code> loops you have to declare this variable externally.<syntaxhighlight lang="javascript" class="code-continue">
let i = 0;            // initial_expressio
let i = 0;            // initial_expressio
while (i <= 5) {      // condition
while (i <= 5) {      // condition
Line 149: Line 149:


=== Do..while loop ===
=== Do..while loop ===
<code>Do..while</code> loops also repeat an action number of times. They are very similar to <code>while</code> loops but they slightly different. <code>Do..while</code> loops always will be executed at least once, because the the condition is evaluated at the end of the iteration.<syntaxhighlight lang="javascript" class="mlw-continue">
<code>Do..while</code> loops also repeat an action number of times. They are very similar to <code>while</code> loops but they slightly different. <code>Do..while</code> loops always will be executed at least once, because the the condition is evaluated at the end of the iteration.<syntaxhighlight lang="javascript" class="code-continue">
let i = 0;            // initial_expressio
let i = 0;            // initial_expressio
do {                   
do {                   
Line 158: Line 158:


=== Infinite loops ===
=== Infinite loops ===
We must avoid such situation that leads to browser crash, etc. Such negative effect could be achieved with all kind of loops in JavaScript that repeat an action number of times.<syntaxhighlight lang="javascript" class="mlw-continue">
We must avoid such situation that leads to browser crash, etc. Such negative effect could be achieved with all kind of loops in JavaScript that repeat an action number of times.<syntaxhighlight lang="javascript" class="code-continue">
let i = 0;               
let i = 0;               
while (i <= 5) {
while (i <= 5) {
Line 164: Line 164:
     // i++;            // in this case 'i' will still '0' forever
     // i++;            // in this case 'i' will still '0' forever
}
}
</syntaxhighlight><syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue">
do {
do {
     // do something...
     // do something...
Line 171: Line 171:


=== For..in loop ===
=== For..in loop ===
<code>For..in</code> loops iterate over the Properties of an Object. <syntaxhighlight lang="javascript" class="mlw-continue">
<code>For..in</code> loops iterate over the Properties of an Object. <syntaxhighlight lang="javascript" class="code-continue">
const demoObject = {
const demoObject = {
     property_1: "value_1",
     property_1: "value_1",
     property_2: "value_2",
     property_2: "value_2",
};
};
</syntaxhighlight><syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue">
for (let key in demoObject)
for (let key in demoObject)
     console.log(key, demoObject[key]);
     console.log(key, demoObject[key]);
</syntaxhighlight><syntaxhighlight lang="shell-session" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="shell-session" class="code-continue">
property_1 value_1
property_1 value_1
property_2 value_2
property_2 value_2
</syntaxhighlight><code>For..in</code> could be used to iterate over the Elements or Items in an Array, but <code>for..of</code> loops are better for this purpose.<syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight><code>For..in</code> could be used to iterate over the Elements or Items in an Array, but <code>for..of</code> loops are better for this purpose.<syntaxhighlight lang="javascript" class="code-continue">
const demoArray = ['value_1', 'value_2', 'value_3'];
const demoArray = ['value_1', 'value_2', 'value_3'];
</syntaxhighlight><syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue">
for (let index in demoArray)
for (let index in demoArray)
     console.log(index, demoArray[index]);
     console.log(index, demoArray[index]);
</syntaxhighlight><syntaxhighlight lang="shell-session" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="shell-session" class="code-continue">
0 value_1
0 value_1
1 value_2
1 value_2
Line 194: Line 194:


=== For..of loop ===
=== For..of loop ===
<code>For..of</code> loops are ideal way in order to iterate over Array Elements or Items. These loops <u>work with the values of the Array elements</u> and we do not to deal with the array index. It is available in [https://www.w3schools.com/js/js_es6.asp ES6] and later.<syntaxhighlight lang="javascript" class="mlw-continue">
<code>For..of</code> loops are ideal way in order to iterate over Array Elements or Items. These loops <u>work with the values of the Array elements</u> and we do not to deal with the array index. It is available in [https://www.w3schools.com/js/js_es6.asp ES6] and later.<syntaxhighlight lang="javascript" class="code-continue">
const demoArray = ['value_1', 'value_2', 'value_3'];
const demoArray = ['value_1', 'value_2', 'value_3'];
</syntaxhighlight><syntaxhighlight lang="javascript" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="javascript" class="code-continue">
for (let element of demoArray)
for (let element of demoArray)
     console.log(element);
     console.log(element);
</syntaxhighlight><syntaxhighlight lang="shell-session" class="mlw-continue">
</syntaxhighlight><syntaxhighlight lang="shell-session" class="code-continue">
value_1
value_1
value_2
value_2
Line 206: Line 206:


=== Break and Continue ===
=== Break and Continue ===
The key words <code>'''break'''</code> and <code>'''continue'''</code> can change the behavior of all kind of loops in JavaScript. Here is an example with <code>while</code> loop:<syntaxhighlight lang="javascript" class="mlw-continue">
The key words <code>'''break'''</code> and <code>'''continue'''</code> can change the behavior of all kind of loops in JavaScript. Here is an example with <code>while</code> loop:<syntaxhighlight lang="javascript" class="code-continue">
let i = 0;
let i = 0;
while (i <= 10) {
while (i <= 10) {
Line 215: Line 215:
}
}
</syntaxhighlight>
</syntaxhighlight>
<syntaxhighlight lang="shell-session" class="mlw-continue">
<syntaxhighlight lang="shell-session" class="code-continue">
0
0
1
1

Latest revision as of 08:30, 26 September 2022

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