Nested if Statements in JavaScript
Nested if statements are if statements that are placed inside another if statement's block. They allow you to check for multiple conditions in a hierarchical manner.
Here's an example of nested if statements:
var age = 25;
var isStudent = false;
if (age >= 18) {
console.log("You are an adult.");
if (isStudent) {
console.log("You are a student."); // This will not be executed in this example
} else {
console.log("You are not a student.");
}
}
Explanation of the example:
var age = 25;: Defines a variableageand assigns it the value25.var isStudent = false;: Defines a variableisStudentand assigns it the valuefalse.if (age >= 18) { ... }: Checks if the variableageis greater than or equal to18.- If the condition
(age >= 18)evaluates totrue, the outerifblock's code executes. - Inside the outer
ifblock:console.log("You are an adult.");: Outputs"You are an adult."to the console.- It then enters another
ifstatement:if (isStudent) { ... }: Checks ifisStudentistrue. SinceisStudentisfalsein this example, the code block inside the nestedifstatement is skipped.- The
elseblock of the nestedifstatement executes instead:console.log("You are not a student.");: Outputs"You are not a student."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>Nested if else example</title>
</head>
<body>
<form action="">
<label for="">Enter a number</label>
<input type="number" id="num">
<button onclick="checksign();" type="button">Submit</button>
</form>
<script>
function checksign(){
var n = Number(document.getElementById('num').value);
if(n>=0){
if(n==0){
document.write("This is a neutral number");
}else{
document.write("This is a positive number");
}
}else{
document.write("This is a negative number");
}
}
</script>
</body>
</html>
Run Code