JavaScript Conditional Statments

JavaScript supports conditional statements which are used to perform different actions based on different conditions.

JavaScript supports the following forms of if ....else statement-
  • if statement
  • if ....else statement
  • if ..else...if statement.

if statement
The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally.

Syntax

The syntax for a basic if statement is as follows:

if(expression)
{
 statement(s) to be executed if expression is true.
}

Example

<html>
<body>
<script type="text/javascript">
<!--
var age = 20;
if( age > 18 ){ document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
</body>
</html>

Output


if..else statement

The 'if...else' statement is the next form of control statement that allows JavaScript to execute statements in a more controlled way.

Syntax

if (expression){

Statement(s) to be executed if expression is true

}

else{

Statement(s) to be executed if expression is false

}


Example


<!DOCTYPE html>

<html>

<head>

<title>HTML Tutorials</title>

</head>

<body>

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

<p id="hello"></p>

<script>

var time = new Date().getHours();

var greeting;

if (time < 10) {

  greeting = "Good morning";

} else if (time < 20) {

  greeting = "Good day";

} else {

  greeting = "Good evening";

}

document.getElementById("hello").innerHTML = greeting;

</script>

</body>

</html>


If..else ..if Statement
The if...else if... statement is an advanced form of if…else that allows JavaScript to make a correct decision out of several conditions.
Syntax:

if (expression 1){

Statement(s) to be executed if expression 1 is true

}

else if (expression 2){

Statement(s) to be executed if expression 2 is true

}

else if (expression 3){

Statement(s) to be executed if expression 3 is true

}

else{

Statement(s) to be executed if no expression is true

}




No comments:

Post a Comment