When we write a conditional statement, the code inside the curly braces only runs if the condition is true
.
But what if the condition is false
? We can write code to handle that scenario as well.
Try this code in the editor:
if (true === false) {
"true is equal to false";
}
else {
"true is not equal to false";
}
The else
keyword can follow up from an if
statement and run code if the condition is not met.
Multiple if
Conditions
We can actually create a chain of conditions to check. Run this code in the editor:
if (1 > 2) {
"1 is greater than 2";
}
else if (1 < 2) {
"1 is less than 2";
}
else {
"1 is equal to 2";
}
The else if
statement can follow up from an if
statement, just like a regular else
statement can. However, the else if
statement has its own condition to check. It will only run if its own condition is true
.
Try changing the example to get different sections of code to run.
Conditions in a Function
Let's see what a conditional statement looks like inside a function. Now we have arguments to work with, like input
below. input
could be any value.
This function will return true
if input
is either true
or false
. If input
is any other value, false
is returned.
Try calling the function with different values to get different results:
function checkIfTrueOrFalse(input) {
if (input === true) {
return true;
}
else if (input === false) {
return true;
}
else {
return false;
}
}
checkIfTrueOrFalse(17);