advanced
 
 

SocialTwist Tell-a-Friend

Introduction Syntax Placement Variables Operators Popup Boxes If Else Statement Switch Case while Loop for Loop break continue Function Array DOM Events Date String Form Validation

JavaScript : Conditional Statement

Conditional statements are used in Javascript to run a section of code if certain codition setisfies.

if Statement
if statement is used to execute the peice of code if some codition is true. it looks like the following:

if (expression)
      statement; 

If the 'expression' in parentheses evaluates to true, the statement is executed; otherwise, the statement is skipped. If two or more lines of code are to be executed, curly braces {} must be used to designate what code belongs in the if statement.
For example,

<html>
<head>
<script type="text/javascript">
<!--
function ifTest() {
   var a=0;
   if (a == 0){
   alert("Hello World");
   }
}
//-->
</script>
</head>
<body>
<input type="button" onclick="ifTest()" value="Click Me" />
</body>
</html>

if else Statement
if else statement is used to execute those section of code, which satisfies the codition is true. it looks like the following:

if (expression1)
      statement;
     else (expression2)
      statement; 

If the 'expression1' in parentheses evaluates to true, the statement1 is executed; otherwise, if the 'expression2' in parentheses evaluates to true, the statement2 is executed. If two or more lines of code are to be executed, curly braces {} must be used to designate what code belongs in the if statement.
For example,

<html>
<head>
<script type="text/javascript">
<!--
function ifElseTest() {
   var a=1;
   if (a == 0){
   alert("A = 0");
   }
   else (a == 1){
   alert("A = 1");
   }
}
//-->
</script>
</head>
<body>
<input type="button" onclick="ifElseTest()" value="Click Me" />
</body>
</html>

Previous            Next
Contact Us
Your Ad Here