...

Web Technologies - JAVASCRIPT

Back to Course

Lesson Description


Lession - #230 Javascript Conditions


Conditional Statements

When writing code, you frequently want to perform different actions based on different decisions. To accomplish this, you can use conditional statements in your code.

The following conditional statements are available in JavaScript:

  • If a specified condition is true, use if to specify a block of code to be executed.

  • If the same condition is false, use else to specify a block of code to be executed.

  • If the first condition is false, use else if to specify a new condition to test.

  • Switch is used to specify a large number of alternative code blocks to be executed.


The If Statement

The if statement is used to specify a block of JavaScript code that will be executed if a condition is met.

Syntax
if (condition>
{
// block of code to be executed if the condition is true
}

<!DOCTYPE html>
<html>
<style>
body{
background-color:#fff8dc;
}
</style>
<body>

<h1>JavaScript if Statement</h1>

<p>Display "Good Morning folks!"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 Night!"; } </script> </body> </html>

Output:

Sorry cannot be displayed
Try it here

The javascript else if Statement

If the first condition is false, use the else if statement to specify a new If the first condition is false, use the javascript if else statement to specify a new condition.

Syntax

if (condition1>
{
//block of code to be executed if condition1 is true
} else if (condition2>
{
// code to be executed if condition1 is false and condition2 is true
}else{
 // block of code to be executed if condition1 and condition2 are both false

<!DOCTYPE html>
<html>
<body>
<style>
body{
background-color:#fff8dc;
}
</style>
<h1>JavaScript if .. else Statement</h1>

<p>A time-based greeting:</p>

<p id="demo"></p>

<script>
const time = new Date(>
.getHours(>
; let greeting; if (time < 10>
{ greeting = "Good morning Friends"; } else if (time < 20>
{ greeting = "Good evening"; } else { greeting = "Good night"; } document.getElementById("demo">
.innerHTML = greeting; </script> </body> </html>

Output:

Sorry cannot be displayed
Try it here