JavaScript if, else, and else if
Conditional Statements
Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
- Use
ifto specify a block of code to be executed, if a specified condition is true - Use
elseto specify a block of code to be executed, if the same condition is false - Use
else ifto specify a new condition to test, if the first condition is false - Use
switchto specify many alternative blocks of code to be executedThe if Statement
Use the
ifstatement to specify a block of JavaScript code to be executed if a condition is true.Example
<html>
<body>
<h2>JavaScript if</h2>
<p>Display "Good day!" if the hour is less than 18:00:</p>
<p id="demo">Good Evening!</p>
<script>
if (new Date().getHours() < 18) {
document.getElementById("demo").innerHTML = "Good day!";
}
</script>
</body>
</html>
The else Statement
Use the
elsestatement to specify a block of code to be executed if the condition is false.Example
- <!DOCTYPE html><html><body><h2>JavaScript if .. else</h2><p>A time-based greeting:</p><p id="demo"></p><script>const hour = new Date().getHours();let greeting;if (hour < 18) {greeting = "Good day";} else {greeting = "Good evening";}document.getElementById("demo").innerHTML = greeting;</script></body></html>
No comments:
Post a Comment