If else statement

Like C or any other core languages , Javascript also have conditional statements which help us in executing one of the statements depending on the correct conditions. If else begins with a condition within if statement. if the statement is true, it is executed, else the 'else' statement is executed. Hope, example will make the things clear.

<html>
<body>
<script type='text/JavaScript'>
var myVar = parseInt(10*(Math.rand));
if (myVar > 5){
   document.getElementById('reqIdname').innerHTML = 'Given no. is greater than 5';
   }
 else {
   document.getElementById('reqIdname').innerHTML = 'Given no. is lesser than 5';
   }
</script>
</body>
</html>

Similarly, we can have a number of else if statement to further extend the loop and check a number of conditions


var myVar = parseInt(10*(Math.rand));
if (myVar == 1){
   document.getElementById('reqIdname').innerHTML = 'Given no. is equal to 1';
   }
 else if(myVar == 2) {
   document.getElementById('reqIdname').innerHTML = 'Given no. is equal to 2';
   }
 else if(myVar == 3) {
   document.getElementById('reqIdname').innerHTML = 'Given no. is equal to 3';
   } 
 else {
   document.getElementById('reqIdname').innerHTML = 'Given no. is none of 1 , 2, or 3';
   }

Switch Statement

Clearly , writing else if a number of times is time consuming and boring. So, we use another method called Switch statement to handle a number of cases with very less code. Silly point to note is that every statement is followed by a break statement and if forgotten each of the statement will be executed simultaneously.


<script type='text/javascript'>

var myVar = parseInt(5*(Math.rand));

switch (myVar)
{
case 0:
  document.write('Number is 0');
  break;
case 1:
  document.write('Number is 1');
  break;
case 2:
  document.write('Number is 2');
  break;
case 3:
  document.write('Number is 3');
  break;
case 4:
  document.write('Number is 4');
  break;
default:
  document.write('none of 0,1,2,3,4');
}
</script>

The default case is executed when none of the case matches with the passed value to the switch statement.

Lets proceed to some core part of Javascript - Event Handling.

Member Login

Member Login




Not a Member? Sign Up!




Login to comment

Be the first to comment on this topic







  


<<< Wanna review

Continue >>>