684
The JavaScript if-else statement is used to execute the code whether condition is true or false. There are three forms of the if statement in JavaScript – these are as follows
- If Statement
- If else statement
- if else if statement
lets go throw these
If statement
This only evaluates the content only if the expression is true. The syntax of the if statement is given below.
Syntax
if ( condition )
{
// statement(s) to be executed
// if condition specified is true
}
A useful example, you can use developer tools in Chrome, Firefox or other browsers to test this out
// check if a number is positive
const number = prompt("Please enter a number: ");
// check if number is greater than 0
if (number > 0)
{
// the body of the if statement
console.log("The number is positive");
}
else Statement
Use the else statement to specify a block of code to be executed if the condition is false.
if (condition)
{
// statements to be executed
// if condition specified is true
}
else
{
// statements to be executed
// if condition specified is false
}
Here is an example of the following
<script>
// check if the number is positive or negative
const number = prompt("Please enter a number: ");
// check if number is greater than 0
if (number > 0)
{
console.log("The number is positive");
}
// if number is not greater than 0
else
{
console.log("The number is either a negative number or 0");
}
</script>
else if Statement
Use the else if statement to specify a new condition if the first condition is false.
if(condition1)
{
// statements to be executed
// if condition1 specified is true
}
else if(condition2)
{
// statements to be executed
// if condition32 specified is true
}
else if(condition3)
{
// statements to be executed
// if condition3 specified is true
}
else
{
//content to be evaluated if no expression is true
}
Here is an example of the above
// check if the number if positive, negative or zero
const number = prompt("Please enter a number: ");
// check if number is greater than 0
if (number > 0)
{
console.log("The number is positive");
}
// check if number is 0
else if (number == 0)
{
console.log("The number is 0");
}
// if number is neither greater than 0 or zero
else
{
console.log("The number is negative");
}