if else statement
The if else statement is an extended version of the if condition. It allows you to write code for both the cases i.e. either the expression returns true or false, you can handle both of them. The if statement will run for the true value while else for the false value.
Syntax:
if (conditional_expression){
// Code statements for true expression evaluation
}
else{
// Code statements for false expression evaluation
}
Example: The below code will explain the use of the if else statement in JavaScript.
const num1 = 45;
const num2 = 8;
if(num1 < 50){
console.log(`${num1} is less than 50`);
}
else{
console.log(`${num1} is greater than 50`);
}
if(num1%num2 === 0){
console.log(`${num2} completely divides ${num1}`);
}
else{
console.log(`${num1} is not divisible by ${num2}`);
}
Output
45 is less than 50 45 is not divisible by 8
JavaScript if else else if
The if…else statement executes a statement if a specified condition is truthy. If the condition is falsy, another statement in the optional else clause will be executed. This structure facilitates decision-making in JavaScript programs.
We have the following conditional statements available in JavaScript:
Table of Content
- if statement
- if else statement
- else if statement
Contact Us