JavaScript Course 3: Control Flow: Difference between revisions
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=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
if (condition) statement; | if (condition) statement; | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="javascript" class=" | <syntaxhighlight lang="javascript" class="code-continue"> | ||
if (condition) | if (condition) | ||
statement; | statement; | ||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="javascript" class=" | <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=" | <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=" | <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=" | <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=" | <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=" | <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=" | 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=" | </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=" | </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=" | 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=" | 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=" | 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=" | <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=" | <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=" | <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=" | 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=" | </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=" | <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=" | </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=" | </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=" | </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=" | </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=" | </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=" | <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=" | </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=" | </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=" | 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=" | <syntaxhighlight lang="shell-session" class="code-continue"> | ||
0 | 0 | ||
1 | 1 |
Latest revision as of 07:30, 26 September 2022
References
- Code with Mosh: The Ultimate JavaScript Mastery Series – Part 1
- W3School: JavaScript if else and else if Statement
- W3School: JavaScript Switch Statement
- W3School: JavaScript Loops
- W3School: JavaScript Iterables
Conditional statements
In JavaScript we have two types of conditional statements:
If..else
Switch..case
The syntax convention is to put the open curly brace '{'
at the same line as the condition.
If..else
if
condition with single and multiple statements.
if (condition) statement;
if (condition)
statement;
if (condition) {
statement_1;
statement_2;
}
else if
condition with single and multiple statements.
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 conditions is evaluated to true.
if (condition_1) {
statement_1;
}
else if (condition_2) {
statement_2;
}
else {
statement_3;
}
Full example:
// 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 compare a value of a variable against a bunch of values. Basic structure:
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');
}
Implementation of If..else
for the same task, which looks better, tidy and simple.
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 different loops in JavaScript serves for repeating an action number of times. These are:
For
loop – repeats an action number of times.While
loop – repeats an action number of times.Do..while
loop – repeats an action number of times.For..in
loop – iterates over the Properties of an Object or over the Elements or Items in an Array.For..of
loop – iterates over the Elements or Items in an Array.
For loop
The for
loops repeat an action number of times, it consists of three statements.
for (initial_expression; condition; increment_expression)
console.log('action to repeat');
- Within the
initial_expression
we declare and initialize a variable, usually the variable is namedi
which is shortcut from index and it is common convention offor
loops:let i = 0
– this is what we called the loop variable. - Within the
condition
we compare the value of the loop variable [i
] with something else. The loop will run as longer itscondition
evaluates to true. For example, if you run the loop 5 times the condition should be:i < 5
. - Within the
increment_expression
we define the rule of the loop variable [i
] incrementation, for example:i++
.
Complete example:
for (let i = 0; i < 5; i++) {
console.log('Hello world!');
console.log('Repeat: ' + (i + 1));
}
Display only odd numbers between 1 to 5 (and in reverse order):
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 also repeat an action number of times. One key difference between for
loops and while
loops is that within the for
loops the loop variable is part of the loop itself. In while
loops you have to declare this variable externally.
let i = 0; // initial_expressio
while (i <= 5) { // condition
console.log(i);
i++; // increment_expression
}
Do..while loop
Do..while
loops also repeat an action number of times. They are very similar to while
loops but they slightly different. Do..while
loops always will be executed at least once, because the the condition is evaluated at the end of the iteration.
let i = 0; // initial_expressio
do {
console.log(i);
i++; // increment_expression
} while (i <= 5); // condition
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.
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 iterate over the Properties of an Object.
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 iterate over the Elements or Items in an Array, but for..of
loops are better for this purpose.
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 ideal way in order to iterate over Array Elements or Items. These loops work with the values of the Array elements and we do not to deal with the array index. It is available in ES6 and later.
const demoArray = ['value_1', 'value_2', 'value_3'];
for (let element of demoArray)
console.log(element);
value_1
value_2
value_3
Break and Continue
The key words break
and continue
can change the behavior of all kind of loops in JavaScript. Here is an example 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