In any programming language, the code needs to make decisions and carry out actions accordingly depending on different inputs. And the same goes for JavaScript, where conditional statements control behavior and determine whether or not pieces of code can run.
There are a couple of conditional statements that you can use in JavaScript, like:
- The
if
statement: Used specify a block of code to be executed, if a specified condition is true. - The
else
statement: Used to specify a block of code to be executed, if the same condition is false. - The
else if
statement: Used to specify a new condition to test, if the first condition is false. - And the
switch
statement: Used to specify many alternative blocks of code to be executed (However this one we’ll not be covering in this section, instead we’ll focus on the previous 3).
The if Statement:
This is probably the most common type of conditional statement you’ll use in JavaScript, which pretty much says "if the condition returns true, run the specified code". And which is generally written in this way:
if (condition) {
// block of code to be executed if the condition is true
}
For example:
if (hour < 12) {
greeting = "Good morning";
}
Note: The
if
is always written in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error.
The else Statement:
When using the if
statement and you want another code to be executed if the condition isn’t true, you can use the else
statement, like so:
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed instead if the condition is false
}
Which is saying that "if the condition returns true, run the first code, else run the second code".
For example:
if (hour < 12) {
greeting = "Good morning";
} else {
greeting = "Good evening";
}
Note: You don’t have to include the
else
and the second curly brace block, and you can just simply use theif
statement, like in the following snippet of code (which is perfectly legal):
if (condition) {
// code to run if condition is true
}
// run some other code
However, you need to be careful in this case, because the second block of code is not controlled by the conditional statement, so it always runs, regardless of whether the condition returns true or false.
The else if Statement:
If you have multiple conditions in your code and in which multiple ones could be true, you can use the else if
statement to specify a new condition if the previous condition is false. Like so:
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
For example:
if (time < 12) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good evening";
} else {
greeting = "Good night";
}
For more on JavaScript conditionals, here’s a quick video that you can watch: