www.pickatutorial.com Computer Tutorials
Top eBooks: C/C++ | C# | Android | Mathematics | Database | Cloud | Graphics | Networking | Oracle | Hardware | AI
Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script| CSS
Lessons JavaScript switch Statement Bookmark and Share
Tutorial Home
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17
Lesson 18
Lesson 19
Lesson 20
Lesson 21
Lesson 22
Lesson 23
Lesson 24
Lesson 25
Lesson 26
Lesson 27
Lesson 28
Lesson 29
Lesson 30
Lesson 31
Lesson 32
Lesson 33
Lesson 34
Lesson 35
Lesson 36
Lesson 37
Lesson 38
Lesson 39
Lesson 40
Lesson 41
Lesson 42
Lesson 43
Lesson 44
Lesson 45
Lesson 46
Lesson 47
Lesson 48
Lesson 49

As has been discussed in one of the previous lessons there are two types of conditional statements available in JavaScript namely if and switch. We have already learned the if statement. In this lesson we will learn the switch statement.

A switch statement allows us to select from a number of code blocks to execute depending upon the result of the expression we pass to the switch statement. The syntax of the switch statement follows:

switch (expression)
{
case label_1:
// code to be executed
[break;]
case label_2:
// code to be executed
[break;]
case label_3:
// code to be executed
[break;]
...
default:
// code to be executed
}

In the above code, as soon as the execution reaches the switch statement, it evaluates the (expression) and tries to match the result to one of the case labels and if a match is found the code under the matched case label is executed. In case no match is found the code following the optional default clause is executed. Note that the break statement in all of the cases above is optional, but if we do not provide break statement then after executing the matched case's code the execution would continue and all of the following cases would also be executed untill a break statement is found or the switch block ends.

Example code follows:

<script type="text/JavaScript">
var day = "Friday";
switch (day)
{
case "Friday":
document.write("Today is Friday ")
break
case "Saturday":
document.write("Today is Saturday ")
break
case "Sunday":
document.write("Today is Sunday ")
break
case "Monday":
document.write("Today is Monday ")
break
case "Tuesday":
document.write("Today is Tuesday ")
break
case "Wednesday":
document.write("Today is Wednesday ")
break
default:
document.write("Today is Thursday ")
}


Next >>> Lesson No. 10: JavaScript Strings





Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.