1.The if Statement:-
Use the if
statement to specify a block of JavaScript code to be executed if a condition is true.
Syntax:-
if (condition) {
// block of code to be executed if the condition is true
}
Example:-
<html>
<body><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>
Result:-Display “Good day!” if the hour is less than 18:00:
Good day!
2.The else statement:-
Use the else
statement to specify a block of code to be executed if the condition is false.
Syntax:-
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example:-
<!DOCTYPE html>
<html>
<body><p>Click the button to display a time-based greeting:</p>
<button onclick=”myFunction()”>Try it</button>
<p id=”demo”></p>
<script>
function myFunction() {
var hour = new Date().getHours();
var greeting;
if (hour < 18) {
greeting = “Good day”;
} else {
greeting = “Good evening”;
}
document.getElementById(“demo”).innerHTML = greeting;
}
</script>
</body>
</html>
Result:-Click the button to display a time-based greeting:
Good day