Conditionals
Conditionals are used to control the behavior of the code - by determine whether or not pieces of code can run.
if/else Statements
The most common type of conditional statements are if and else statements.
If the condition is true, the code in the following set of curly braces will execute. Otherwise, the code contained within the curly braces following the else statement will execute instead.
if (condition) {
return this code if the condition is true
} else {
return this code instead
}
else if
To consider additional choices the else if statement is used. It is put between if and else statements.
if(condition) {
} else if (other condition) {
} else {
}
switch Statements
The switch statement executes a block of code depending on different cases. A switch
statement for a larger number of conditions is exactly the right advice when considering performance.
let fruit = 'apple';
switch (fruit) {
case 'banana':
console.log('wrong');
break;
case 'kiwi':
console.log('wrong');
break;
case 'apple':
console.log('Right');
break;
case 'grape':
console.log('wrong');
break;
default:
console.log('An unknown value');
}
ternary operator
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as a shortcut for the if statement.
( condition ) ? run this code : run this code instead
List of Resources
ITNext: JavaScript Fundamentals: Using Conditionals
MDN: Conditional (ternary) operator
O'REILLY: Chapter 4. Algorithms and Flow Control