In this post, we will be learning about JavaScript conditional statements.
Conditional Statements
Conditional statements: what are they used for?
The purpose of conditional statements is to say: if a certain condition inside the () is true, then execute the code inside the {}. The reason they are used is in your code you will often want to perform different actions depending on whatever condition is met(e.g. if a variable equals to something).
Conceptually, conditional statements in JavaScript are the same as they are in any other language.
Some common conditional statements include:
If Statements
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
If a certain condition is true, then execute the following code below.
JavaScript Code
var x= 23;
if(x>10)
{document.write("X is greater than 10");
}
Result
Else if Statements
Syntax
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
}
Another type of conditional is the if else statement.
Else if statements essentially say: "check if condition 1 is true, if it is true, execute the code in its {} and ignore the other else if/elses.
If it is not, then check condition 2 and execute code block 2 inside the {} if it is true".
We do this for all the listed conditions until at least one of them is true or none of them are true.
If, however, more than one of the conditions ends up being true, then we only execute the block of code for the first true condition we encounter: the remaining code does not matter.
JavaScript Code
x = 22;
if(x>32)
{
document.write("X is greater than 32");
}
else if(x<32)
{
document.write("X is not greater than 32");
}
Result
Else Statements
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
JavaScript Code
x = 11;
if(x>20)
{
document.write("X is greater than 20");
}
else
{
document.write("X is not greater than 20");
}
Result
If we want a block to execute if none of the conditions are met, we use an else statement. In essence, else statements state: if all the condition above aren’t met, execute this block of code.