spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / programming / javascript / diaries / 5

[previous] [next]

Senior Consultant/Information Security - permanent position (TX)
Next Step Systems
US-TX-Irving

Justtechjobs.com Post A Job | Post A Resume
Developer News
Mandrake Linux Founder Back, Virtually
Amazon: We're a Technology Company
Sun Expands MySQL With Closed Source

The JavaScript Diaries: Part 5

The Switch Statement

The switch statement provides the user with several options and returns a result based upon the user's selection. It resembles the if/else statement but is more manageable and efficient. The switch statement doesn't need to do a comparison for each option. It merely looks for a match with the expression and executes the code within the case statement. There is only one set of curly brackets. Formatting the code, as shown below, makes reading (and debugging) easier. The style of the format is optional; however, it makes good programming sense to choose some type formatting to help eliminate errors. The format we will use is:

  switch(expression) {
    case option1:
      statement;
      break;
    case option2:
      statement;
      break;
    case option3:
      statement;
      break;
    default:
      statement;
      break;
  }

Basically, the switch statement compares the expression in the parentheses with the option listed in each case statement. When it finds one that matches, it carries out the instructions given in the case statement. Usually each case statement ends with a break or a return command. That way, if the condition is true, the switch statement will stop executing and return to the main script. Otherwise, each case statement after the one that matches the parameters would be executed. The switch statement can also end with a default statement, which would give a value without being compared to the expression. If there is no default statement, and a match cannot be found within the case options, execution will return to the main script. Here's an example of a switch statement:

var theName="Fred";
switch (theName) {
  case "George" :
    alert("George is an OK name");
    break;
  case "Fred" :
    alert("Fred is the coolest name!");
    alert ("Hi there, Fred");
    break;
  default :
    alert(theName + " is an interesting name you have there.");
      break;
}

This is one based on the if/else statement we made previously. In this one, the switch statement is using the Boolean term true to determine the value of the case statement. Here's what is happening when the script is executed:

  • The variable theName is declared and initialized using as a value the data string "Fred."
  • Next, a switch statement is begun using the variable we just declared as the expression. When the switch statement is executed, the JavaScript interpreter will compare each case option with the expression listed in the parentheses following the switch reserved word, in this instance that would be the value of the variable theName.
  • The statement will find a match in the second case statement. It will then display an alert window with the string, "Fred is the coolest name!" Once that window is closed, it will display another alert window with the string, "Hi there, Fred." It will then encounter the break statement and will stop execution. (If this were part of a larger script, execution would return to the main script.)

Let's take a look at a script we wrote earlier in this installment. We had used else/if statements for that script. This time we'll use a switch statement:

function meeting() {

  var text = "The meeting this week will be at ";
  var nowDate = new Date();
  var currDate = nowDate.getDate();

  switch(true) {
  case (currDate < 5) && (currDate > 0):
    document.write(text + "Steve's house");
    break;
  case (currDate < 12) && (currDate > 4):
    document.write(text + "Nancy's house");
    break;
  case (currDate < 19) && (currDate > 11):
    document.write(text + "Mike's house");
    break;
  default:
    document.write(text + "Sally's house");
    break;
  }
}

This script accomplishes the same thing as our previous one but in a different manner. Everything is the same up to the switch statement. This is where the change occurs but it's not all that different. When the script finds a case statement that is true, as given in the switch statement, it will execute the statement and then stop. As I said, this is the same as the else/if statement we presented earlier only it's a little easier to understand. Let's take a look at another one:

  var yourGrade=prompt("Enter the student's grade","Use CAPITALS");

  switch(yourGrade) {
    case 'A':
      alert("Excellent");
      break;
    case 'B':
      alert("Good");
      break;
    case 'C':
      alert("OK");
      break;
    case 'D':
      alert("Mmmmm....");
      break;
    case 'F':
      alert("You must do better than this");
      break;
    default:
      alert("You need to enter either A, B, C, D, or F");
      break;
  }

You can add additional case statements to allow for further conditions in order to obtain the same result. For instance, if you wanted to allow for upper and lower case letters in the script above, you could format each case statement as follows:

    case 'A':
    case 'a':
      alert("Excellent");
      break;

You can also use values in switch statements, as shown below:

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;
}
Modifying our previous script using the date, we could use the switch statement to obtain the date of the week using the getDay object instead of the getDate:
var dat = new Date()
today=dat.getDay()

switch (today) {
  case 0:
    document.write("Today is Sunday")
    break
  case 1:
    document.write("Today is Monday")
    break
  case 2:
    document.write("Today is Tuesday")
    break
  case 3:
    document.write("Today is Wednesday")
    break
  case 4:
    document.write("Today is Thursday")
    break
  case 5:
    document.write("Today is Friday")
    break
  case 6:
    document.write("Today is Saturday")
    break
}
home / programming / javascript / diaries / 5

[previous] [next]

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Whitepapers and eBooks

Symantec Whitepaper: Converging System and Data Protection for Complete Disaster Recovery
Intel Whitepaper: Comparing Two- and Four-Socket Platforms for Server Virtualization
IBM Solutions Brief: Go Green With IBM System xTM And Intel
HP eBook: Simplifying SQL Server Management
IBM Contest: Are You the Next Superstar? Join the "Search for the XML Superstar" Contest to Find Out
Intel PDF: Quad-Core Impacts More Than the Data Center
Intel PDF: Virtualization Delivers Data Center Efficiency
Go Parallel Article: PDC 2008 in Review
Avaya Article: Communication-Enabled Mashups: Empowering Both Business Owners and IT
Intel Whitepaper: Building a Real-World Model to Assess Virtualization Platforms
PDF: Intel Centrino Duo Processor Technology with Intel Core2 Duo Processor
Microsoft Article: Build and Run Virtual Machines with Hyper-V Server 2008
  Go Parallel Article: Q&A with a TBB Junkie
IBM Whitepaper: Innovative Collaboration to Advance Your Business
Internet.com eBook: Real Life Rails
IBM eBook: The Pros and Cons of Outsourcing
Internet.com eBook: Best Practices for Developing a Web Site
IBM CXO Whitepaper: The 2008 Global CEO Study "The Enterprise of the Future"
Avaya Article: Call Control XML in Action - A CCXML Auto Attendant
IBM CXO Whitepaper: Unlocking the DNA of the Adaptable Workforce--The Global Human Capital Study 2008
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Symantec Whitepaper: Comprehensive Backup and Recovery of VMware Virtual Infrastructure
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
webref The latest from WebReference.com Browse >
Popular JavaScript Framework Libraries: An Overview - Part 3 · Accessing Your MySQL Database from the Web with PHP · Working with the DOM Stylesheets Collection
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Fixing MySQL Replication · Firewall Guide: First Steps to Securing the Enterprise · VoxOx Tames the Tumultuous Communications Tangle

Created: June 10, 2005

URL: