JavaScript else if Ladder
An "else if ladder" is a series of if, else if, and optionally else statements used to check multiple conditions sequentially.
Here's an example of an else if ladder:
var num = 7;
if (num > 10) {
console.log("The number is greater than 10.");
} else if (num > 5) {
console.log("The number is greater than 5 but less than or equal to 10.");
} else if (num > 0) {
console.log("The number is greater than 0 but less than or equal to 5.");
} else {
console.log("The number is less than or equal to 0.");
}
Explanation of the example:
var num = 7;: Defines a variablenumand assigns it the value7.- The else if ladder starts with an
ifstatement:if (num > 10) { ... }: Checks ifnumis greater than10. Since7is not greater than10, this condition is false.- It then moves to the next
else ifstatement:else if (num > 5) { ... }: Checks ifnumis greater than5. Since7is greater than5, this condition is true.- The corresponding code block executes:
console.log("The number is greater than 5 but less than or equal to 10.");: Outputs"The number is greater than 5 but less than or equal to 10."to the console.
All in one Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Else if ladder example</title>
</head>
<body>
<form action="">
<label for="">Enter a weekday number</label>
<input type="number" id="daynum">
<button onclick="weekday();" type="button">Submit</button>
</form>
<script>
function weekday(){
var day = Number(document.getElementById('daynum').value);
if(day==1){
document.write("Monday");
}else if(day==2){
document.write("Tuesday");
}else if(day==3){
document.write("Wednesday");
}else if(day==4){
document.write("Thursday");
}else if(day==5){
document.write("Friday");
}else if(day==6){
document.write("Saturday");
}else if(day==7){
document.write("Sunday");
}else{
document.write("Wrong Entry");
}
}
</script>
</body>
</html>
Run Code