JavaScript IF Else - Conditional Statements in JavaScript: if, else, and else if
JavaScript if, else, and else if
- Conditional statements are used to perform different type of action is based on the different conditions.
- In JavaScript we have the following conditional statements.
- Use
if
to specify a block of code to be executed, if a specified condition is true - Use
else
to specify a block of code to be executed, if the same condition is false - Use
else if
to specify a new condition to test, if the first condition is false - Use
switch
to specify many alternative blocks of code to be executed
The if Statement

Sample Code
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if</h2>
<p>As per condition the value will be changed</p>
<p id="demo"></p>
<script>
if (1 < 18) {
document.getElementById("demo").innerHTML = "The condition is correct";
}
</script>
</body>
</html>
Output
JavaScript if
As per condition the value will be changed
The condition is correct
The else Statement
- Use the else statement to specify a block of code to be executed if the condition is false.

Sample Code
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if .. else</h2>
<p>A time-based greeting:</p>
<p id="para"></p>
<script>
const hour = new Date().getHours();
let greeting;
if (hour < 18) {
wishes = "Good day";
} else {
wishes = "Good evening";
}
document.getElementById("para").innerHTML = wishes;
</script>
</body>
</html>
Output
JavaScript if .. else
A time-based greeting:
Good evening
The else if Statement
Sample Code
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript else if</h2>
<p>As per condition the value will be changed</p>
<p id="demo"></p>
<script>
let score = 75;
if (score >= 90) {
document.getElementById("demo").innerHTML = "You got an A!";
} else if (score >= 80) {
document.getElementById("demo").innerHTML = "You got a B!";
} else if (score >= 70) {
document.getElementById("demo").innerHTML = "You got a C.";
} else {
document.getElementById("demo").innerHTML = "You need to study harder.";
}
</script>
</body>
</html>
Output
JavaScript else if
As per condition the value will be changed
You got a C.