Javascript If Else Statement

Javascript If Statement

Sometimes we reqiure to execute certain statement when specified condition true.

Syntax

<script type="text/javascript">
if (condition)
{
   //code that will run if the condition is true
}
</script>

Javascript If Statement Example

<!DOCTYPE html>
<html>
<head>
<title>My first JSON Object Code</title>
<SCRIPT LANGUAGE="JavaScript">
var age = 18
if (age < 20)
{
   document.write('Invalid person for test');
}
 </SCRIPT>
 </HEAD>
<BODY>
</BODY>
</HTML>

If..Else Statement

When specified condition fails the else statement will get execute.

Syntax

<script type="text/javascript">
if (condition)
{
   //code that will run if the condition is true
}
else
{
  //code that will run if the condition is false
}
</script>

Javascript If Statement Example

<!DOCTYPE html>
<html>
<head>
<title>My first JSON Object Code</title>
<SCRIPT LANGUAGE="JavaScript">
var age = 18
if (age < 20)
{
   document.write('Invalid person for test');
}
else
{
   document.write('Valid person for test');
}
 </SCRIPT>
 </HEAD>
<BODY>
</BODY>
</HTML>

If..Else If Statement

When there are situations when we need to test several conditions then we will use else if condition.

Syntax

<script type="text/javascript">
if (condition1)
{
   //code that will run if the condition1 is true
}
else if(condition2)
{
  //code that will run if the condition2 is true
}
else if(condition3)
{
  //code that will run if the condition3 is true
}
else
{
  //code that will run if the all contitions fails
}
</script>

Javascript If..Else If Statement Example

<!DOCTYPE html>
<html>
<head>
<title>My first JSON Object Code</title>
<SCRIPT LANGUAGE="JavaScript">
var number = -1;
if (number > 0)
{
   document.write('Positive number');
}
else if(number < 0)
{
   document.write('Negetive number');
}
else
{
document.write('Not a number');
}
 </SCRIPT>
 </HEAD>
<BODY>
</BODY>
</HTML>