Conditional statements¶
Conditional statements are mechanisms built into the language that execute the selected code, depending on whether the value of an expression is true or false. JavaScript offers the following possibilities:
if
if
-else
else if
switch
if¶
These instructions have a similar syntax to that you already know from Java. I.e., after the keyword if
, the appropriate condition is given in parentheses. If it evaluates to true
, the code from the inner block (inside the {
and }
) will be executed, otherwise, it is omitted, e.g:
if (1 === 1) {
console.log('Yes, 1 equals 1!'); // this line will be displayed on the screen
}
if ([1, 2].includes(1)) {
console.log('Yes, this array contains the number 1'); // this line will be displayed on the screen
}
if ('') {
console.log('an empty string is evaluated on false'); // this line will NOT be displayed on the screen
}
if ({} && []) {
console.log('An empty array and an empty object evaluate themselves as true'); // this line will NOT be displayed on the screen
}
if (null || undefined) {
console.log('null and undefined evaluate themselves on false'); // this line will NOT be displayed on the screen
}
if else and else¶
Each conditional statement if
can have multiple code blocks defined, which will be executed when each of the previous conditions following the word if
is evaluated as false
. These blocks are else if
. It is also possible to define a code block after the keyword else
, which will be executed when none of the previous conditions in blocks of if
or else if
are not met, e.g:
const number = 5;
if (number % 5 === 4) {
console.log('is your number 9?');
} else if (number % 5 === 3) {
console.log('The remaiander is 3!');
} else if (number > 5) {
console.log('I dont think its possible');
} else {
console.log('All \'ifs \ were false so we landed here');
}
Switch¶
The switch
instruction in the JavaScript is used to select the appropriate block to be executed, based on a certain value. Each possibility is printed with the keyword case
and then, after a colon, the code that should be executed. A block of such a code can be terminated with the break
instruction, which will exit the switch
instruction. This statement also offers the possibility to define a block of default
, which will be executed if the value does not match any of the case
blocks defined.
Example:
const value = 5;
switch (value) {
case 2:
case 4:
console.log('I am definately even and lower than 5');
break;
case 1:
case 3:
console.log('I am odd and lower than 5');
break;
case 5:
console.log('I am equal to 5');
break;
default:
console.log('I am greater than 5');
}
// 'I am equal to 5' will be displayed
__NOTE_:_ The instructions of
if else
together withelse
work the same way as theswitch
instructions and can be used interchangeably. If you use theif else
instructions, when the number of blocks ofif else
increases significantly, consider whether theswitch
instruction will not be clearer.