| Javascript case statement
Case statement can be used to control different possibilities of a condition.
Use of case statement is recommended when single condition could have range
of possibilities. For example, getDate is a method that could return any day
of the week. Case statement can be used to determine and display a message related
to current day.
The syntax for case statement is as follows:
switch(condition) { case value:
Action statement }
The case value is executed when the condition is true.
If no match is found, then default condition is executed if specified.
The following example explains use of case statement to get current day:
<html>
<body>
<script type="text/javascript">
<!--
var dat = new Date()
today=dat.getDay()
switch (today)
{ case 2: alert("It's Monday")
break case 3: alert("It's Tuesday")
break case 4: alert("It's Wednesday")
break case 5: alert("It's Thursday")
break case 6: alert("It's Friday")
break case 7: alert("It's Saturday")
break case 1: alert("It's Sunday")
break } //-->
</script> </body> </html>
|
In this example, we declared a variable dat and set it to
date object.
getDay is a method that has access to the days of the week in numbers 1-7.
switch sets the condition to test and case tests the value and
executes when it's true.
break breaks the condition.
Since the condition is always true, hence everyday is a day; there is no need of
specifying default statement to execute when there is no match. This example
executes when the page is loaded since it's in the body section of the
document. The following example asks the user
to enter a number between 1 and 3.
If wrong number entered, default value is executed.
|
<body>
<script type="text/javascript">
var n=prompt("Enter a number between 1 to 3:",0)
switch(n)
{ case(n="1"): alert("You typed "+n);
break case(n="2"): alert("You typed "+n);
break case(n="3"):
alert("You typed "+n); break
default: alert("Wrong number"); break
} </script> </body>
|
If statement
Loops
|