JavaScript if-else statement will execute block according to the condition of a Boolean expression. That can only be one of the blocks either if or else.
But we can change our code so that both the statements inside the if block and the else block gets executed, for the same condition.
JavaScript if and else both executed
Simple example code assigns an opposite value in if block to execute else and call the function again. Using not operator and && and for multiple conditions.
<!DOCTYPE html>
<html>
<body>
<script>
var age = true;
var n = 0;
function ifElse(argument) {
if (age && n <= 1) {
console.log("if condition is", age);
n = n+1;
age = !age;
ifElse()
} else {
console.log("if condition is", age);
}
}
ifElse();
</script>
</body>
</html>
Output:
Do comment if you have any doubts or suggestions on this js if else topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version