Conditions are used to do different actions based on the different conditions.
During programming often it is required to perform different actions based on different criteria to finalize the decision.
Following conditional statements are available in JavaScript
if statement is used to specify code block to be execute if the condition evaluates to true.
if (condition) { // statements to be executed if the condition is true. }
JavaScript statements are is case sensitive, so If or IF will produce JavaScript error.
<!DOCTYPE html>
<html>
<body>
Student gets Grade A if marks > 90.
<p id="text">Grade B</p>
<script>
var marks= 95;
if(marks > 90) {
document.getElementById('text').innerHTML = 'Grade A';
}
</script>
</body>
</html>
There can be more than one and any number of elseif statements
else statement is used to specify code block to be execute if the condition evaluates to false.
if (condition) { // statements to be executed if the condition is true. } else { // statements to be executed if the condition is false }
<!DOCTYPE html>
<html>
<body>
Student A gets
<p id="text">Grade B</p>
Student B gets
<p id="text1">Grade B</p>
<script>
var studentAmarks = 95;
if(studentAmarks > 90) {
document.getElementById('text').innerHTML = 'Grade A';
} else {
document.getElementById('text1').innerHTML = 'Grade B';
}
var studentBmarks = 85;
if(studentBmarks > 90) {
document.getElementById('text').innerHTML = 'Grade A';
} else {
document.getElementById('text1').innerHTML = 'Grade B';
}
</script>
</body>
</html>
elseif statement is used to specify code block to be execute if the first condition evaluates to false.
if (condition) { // statements to be executed if the condition is true. } else if (condition1) { // statements to be executed if the condition is false. } else { // statements to be executed if the both above condition is false. }
<!DOCTYPE html>
<html>
<body>
Student A gets
<p id="text">Grade B</p>
Student B gets
<p id="text1">Grade B</p>
<script>
var studentAmarks = 75;
var studentBmarks = 95;
document.getElementById('text').innerHTML = getGrade(studentAmarks);
document.getElementById('text1').innerHTML = getGrade(studentBmarks);
function getGrade(marks) {
if(marks > 90) {
return 'Grade A';
} else if(marks > 80) {
return 'Grade B';
} else if(marks > 70) {
return 'Grade C';
} else if(marks > 60) {
return 'Grade D';
} else {
return 'Fail';
}
}
</script>
</body>
</html>