spacer

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

home / programming / javascript / diaries / 5

[previous] [next]

Web Project Manager
Aquent
US-PA-Collegeville

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

Conditional Expressions

There is another method for writing conditional statements, so long as it is a true or false statement. This method uses the conditional operator ( ?: ). Consider the following script:

  var yourAge = prompt("Please enter your age:", "");

  if (yourAge >= 18) {
    alert("You are a grownup");
  }
  else {
    alert("You are a minor");
  }

We've seen this type of script before so we don't need to go into how it works. Using a conditional statement, the same script could be written:

  var yourAge = prompt("Please enter your age:", "");
  var yourStatus = (yourAge >= 18) ? "grownup" : "minor"
  alert("Your are a " + yourStatus)

Here, we declare and initialize the variable yourAge, as in the previous script, but in this case, the entire if/else statement is accomplished on one line. The second line declares and assigns a value to the variable yourStatus depending upon the conditional statement that follows it. The conditional statement reads: "If the variable yourAge is greater than or equal to 18 then the value of the variable yourStatus is 'grownup,' otherwise the value is 'minor.'"

This can save a lot of time and effort in coding a script. Remember though, it only works if you have a true/false statement.

Nesting

A conditional statement can also be contained within another conditional statement. This is called nesting. Consider the following script (with credit to John Pollock):

  var have_cookbook="yes";
  var meatloaf_recipe="yes";

  if (have_cookbook=="yes") {
    if (meatloaf_recipe=="yes") {
      alert("Recipe found");
    }
    else {
      alert("Have the book but no recipe");
    }
  }
  else {
    alert("You need a cookbook");
  }

Let's look at how this script is executed:

  1. Two variables, have_cookbook and meatloaf_recipe, are declared and initialized, each with a value of "yes."
  2. The conditional statement begins by asking if the variable have_cookbook is equal to "yes." (Remember from our previous section, the equal sign [ = ] is an assignment operator and the double equal sign [ == ] is a comparison operator.)
  3. If the statement is true, then another nested conditional statement begins. It asks if the variable meatloaf_recipe is equal to "yes."
    1. If that statement is true, an alert window will display, "Recipe found." Another way of saying it is: "If the variable have_cookbook is equal to 'yes' and the variable meatloaf_recipe is also equal to 'yes,' then display an alert window that says 'Recipe found.'"
    2. If the statement is false, an alert window will display, "Have the book but no recipe." Another way of saying it is: "If the variable have_cookbook' is equal to 'yes' and the variable meatloaf_recipe is equal to no, then display an alert window that says 'Have the book but no recipe.'"
  4. If the variable have_cookbook is not equal to "yes," then the nested statement will be skipped altogether and the final else statement will be executed, displaying an alert window that says, "You need a cookbook."

It sounds a little complicated but if you look closely you'll see it's pretty straightforward.

You could also nest a conditional statement within the bottom (outside) else block. In other words, the same nested block that you see above could also be done in the other part of the statement:

  var have_cookbook = prompt('Do you have a cookbook?','');
  var meatloaf_recipe = prompt('Do you have a meatloaf recipe?','');
  var have_web_access = prompt('Do you have access to the Web?','');

  if (have_cookbook=="yes") {
    if (meatloaf_recipe=="yes") {
      alert("Recipe found");
    }
    else {
      alert("Have the book but no recipe");
    }
  }
  else {
    if (have_web_access=="yes") {
      alert("Find the recipe on the Web");
    }
    else {
      alert("You need a good cookbook");
    }
  }

There's no limit to the number of nested statements you can use. While they seem to be a bit confusing, if taken a step at a time, they can be a very powerful tool.

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: