The control flow is the order in which the computer executes statements in a script.
if…else
if ( condition )
statement1
// With an else clause
if ( condition )
statement1
else
statement2
- condition – An expression that is considered to be either truthy or falsy.
- statement1 – Statement that is executed if condition is truthy. Can be any statement, including further nested
if
statements. - statement2 – Statement that is executed if condition is falsy and the
else
clause exists. Can be any statement, including block statements and further nestedif
statements.
Ex:
1 2 3 4 5 6 7 8 | var isRaining = false; if (isRaining) { alert("Don't forget an umbrella!"); } else { alert("No need for an umbrella."); } |
Multiple if...else
statements can be nested to create an else if
clause. Note that there is no elseif
(in one word) keyword in JavaScript.
statement1
else if ( condition2 )
statement2
else if ( condition3 )
statement3
// …
else
statementN
statement1
else
if ( condition2 )
statement2
else
if ( condition3 )
statement3
// …
1 2 3 4 5 6 7 | // Using if...else if (cipherChar === fromChar) { result += toChar; x++; } else { result += clearChar; } |
1 2 3 4 5 6 7 8 | // Using else if if (x > 50) { /* do something */ } else if (x > 5) { /* do something */ } else { /* do something */ } |
switch
The switch
statement is a conditional statement that literally switches over given blocks of code depending on whether they meet a given criterion.
case match1:
statements;
case match2:
statements;
/* … */
case matchN:
statements;
}
- expression – An expression whose result is matched against each
case
clause. - casematch1 – If the value of
expression
matches the value of anymathN
, execution starts from the first statement after thatcase
clause until either the end of theswitch
statement or the first encounteredbreak
.
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | const foo = 0; switch (foo) { case -1: console.log("negative 1"); break; case 0: // Value of foo matches this criteria; execution starts from here console.log(0); // Forgotten break! Execution falls through case 1: // no break statement in 'case 0:' so this case will run as well console.log(1); break; // Break encountered; will not continue into 'case 2:' case 2: console.log(2); break; default: console.log("default"); } // Logs 0 and 1 |
The default clause
The default
keyword is used to specify the default clause to execute in a switch
statement when neither of the given cases matches.
case match1:
statements;
case match2:
statements;
/* … */
case matchN:
statements;
default:
statements;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 | var char = 'a'; switch (char) { case 'a': case 'e': case 'i': case 'o': case 'u': console.log('Vowel'); break; default: console.log('Consonant'); } |