Login | Register | FAQ
Anonymous


Lesson 6: Even Smarter Scripts with if…else and switch

By Maria Antonietta Perna

Now that our JavaScript code can calculate, compare, and determine true and false conditions, things start looking a lot more interesting.

The days of dumb message boxes popping up are long gone, the new era of smart message boxes has begun.

In this lesson you're going to inject the power of choice into your scripts with conditional statements. These statements enable your script to evaluate given conditions on the basis of which to execute one or more actions. More specifically, you're going to learn how to use:

  • if statements;
  • if ... else statements;
  • if ... else if ... else statements;
  • switch statements.

In the process, you're also going to learn how to use shortcut assignment operators.

if Statement

The if keyword is used in JavaScript to perform a basic test for the truth or falsity of a given condition and execute a piece of code accordingly. Here's its structure:

	
	  //if the condition in brackets is true
	
	  if (condition)
	
	  {
	
	  //do some stuff here
	
	  }
	
	  

Let's translate the code

Translated into English, the if statement above says:

"Hey browser, if the condition in the round brackets is true, execute the commands between those odd curly braces. If the condition is not true, then ignore everything and move on!"

Important: do not forget either the brackets ( ) or the braces { }.

if ... else statement

Use this statement to execute a command if the condition is true and another command if the condition is false. Here's its structure:

	
	  //if the condition is true
	
	  if (condition)
	
	  {
	
	  //do this stuff
	
	  }
	
	  //otherwise
	
	  else
	
	  {
	
	  //do this other stuff
	
	  }
	
	  

if ... else if ... else statement

Use this statement if you want your code to evaluate several conditions on the basis of which to execute the appropriate commands. Here's its structure:

	
	  //if the condition is true
	
	  if (condition)
	
	  {
	
	  // do this stuff
	
	  }
	
	  //if this other condition is true instead
	
	  else if (condition)
	
	  {
	
	  // do this other stuff
	
	  }
	
	  //if none of the above condition is true
	
	  else
	
	  {
	
	  // do this instead
	
	  }
	
	  

switch statements

In alternative to an if ... else if ... else statement you can switch to a ... well a switch statement. Here's its basic structure:

	
	  //condition to evaluate
	
	  switch(condition)
	
	  {
	
	  //in this case do this
	
	  case 1:
	
	  execute code block 1
	
	  //stop here: no need to keep going
	
	  break;
	
	  //in this other case do that
	
	  case 2:
	
	  execute code block 2
	
	  //stop here: no need to keep going
	
	  break;
	
	  //otherwise fall back on this
	
	  default:
	
	  code to execute when all previous conditions evaluate to false
	
	  }
	
	  

It's time to put your new knowledge to work right away. In this try out you're going to check a product price and decide whether to apply a discount. Prepare a new HTML document and get coding!

Try out: check product price with if

	
	  <!DOCTYPE html>
	  <html>
	  <head>
	  <title>Lesson 6: Even Smarter Scripts with if…else and switch</title>
	  </head>
	  <body>
	  <h1>Lesson 6: if statements</h1>
	  
	  <script type="text/javascript">
	
	  //store 5% discount value in a var
	
	  var discountRate = 0.05;
	
	  //store price of 1 apple in a var with a value of 2
	
	  var applePrice = 2;
	
	  //store quantity value in a var
	
	  var quantity = 5;
	
	  //declare a var for the discounted total value
	
	  //because we don't know the value we initialize it with 0
	
	  var discountedTotal = 0;
	
	  //store the value of the total in a var
	
	  //you use the ( * ) multiplication operator to calculate the total
	
	  //and the ( = ) assignment operator to assign the value to the var
	
	  var total = quantity * applePrice;
	
	  //use if to check the total is entitled to a discount
	
	  //if total is greater or = to 10 it's entitled
	
	  if (total >= 10)
	
	  {
	
	  alert("You're entitled to a discount!");
	
	  //apply 5% discount on the total
	
	  //and assign it to discountedTotal var
	
	  //Take note: multiplication is in brackets because it has to be
	
	  //performed before subtraction (remember the good old school math?)
	
	  discountedTotal = total - (discountRate * total);
	
	  //create a var to store text to display to user
	
	  var infoText = "You'll get your delicious apples at $" + discountedTotal;
	
	  //you add more text to the same infoText var with a shortcut assignment operator
	
	  //this technique is useful when you have long text strings to manipulate
	
	  infoText += " instead of at $" + total;
	
	  //display message to the user
		
	  document.write(infoText);
	
	  }
	  
	  </script>
		
	  </body>
	  </html>
	
	  

Save your work, run the page in the browser, and enjoy your discount!

Questions, questions, questions

It's almost like I can hear you saying something like:

Hey, what's going on there? What's that += sign all about?

Here's the answer:

Shortcut operators

When you add several values to a variable, a shortcut operator is very handy.

The expression x += 2 is the same as x = x + 2.

As you can see, the given value of x is taken as the starting point, 2 is added to it, and the resulting value is reassigned to x. Using a shortcut operator spares you from having to retype x.

When applied to the code snippet above, the expression infoText += " instead of at $" is the same as infoText = infoText + " instead of at $". If we simply use an ( = ) assignment operator in this case, the text already stored in infoText will be wiped out by the new value. But this is not what we want in this script.

Handy shortcuts are also available to all other mathematical operators:

  • -=
  • *=
  • /=
  • %=

Try out: check product price with if ... else

Just after the closing curly brace } from the previous example, add the following snippet.

	
	  else
	
	  {
	
	  alert("Sorry, you're not entitled to a discount");
	
	  var infoText = "Your delicious apples cost $" + total;
	
	  document.write(infoText);
	
	  }
	
	  

Change the value in the quantity variable to be less than 5, save your work and run the page in the browser. Now, JavaScript should give you the not so good news that you're not entitled to a discount.

Try out: check product price with if ... if else ... else

Still using the previous example, between the first if block and the last else block, insert the following else if block.

	
	  //if the total equals to 8
	
	  else if (total == 8)
	
	  {
	
	  alert("Just add a couple more apples and get your discount!");
	
	  var infoText = "Be a sport, buy a bit more and pay a bit less";
	
	  document.write(infoText);
	
	  }
	
	  

Change the quantity variable to be 4, save your work and run the page in the browser. Now you should fall for the persuasive power of such a great discount.

Your code can detect if the purchase qualifies for a discount, if it almost qualifies for a discount, and finally if the discount is inapplicable by a long shot. In each case, your code can take appropriate action.

Have fun practicing with if ... else if ... else statements, and shortcut operators.

Try out: days of the week with switch

Now get a fresh HTML document ready and type the following code block:

	
	  <!DOCTYPE html>
	  <html>
	  <head>
	  <title>Lesson 6: Even Smarter Scripts with if…else and switch</title>
	  </head>
	  <body>
	  <h1>Lesson 6: switch</h1>
	  
	  <script type="text/javascript">
	
	  //pick a day of the week and store it in a var
	
	  var today = "Friday";
	
	  //check today var value and act accordingly
	
	  switch(today)
	
	  {
	
	  //in case value corresponds to Saturday or to Sunday do this:
	
	  case "Saturday":
		
		case "Sunday":
	
	  alert("It's the weekend: great!");
	
	  document.write("Today is " + today);
	
	  //no need to keep going:
	
	  break;
	
	  //in case value corresponds to Friday do this
	
	  case "Friday":
	
	  alert("Almost weekend time!");
	
	  document.write("Today is " + today);
	
	  //no need to keep going
	
	  break;
	
	  //in all other cases do this instead
	
	  default:
	
	  alert("Just an ordinary weekday: keep up the good work");
	
	  document.write("Today is " + today);
	
	  }
	
	  </script>
		
	  </body>
	  </html>
	
	  

Save your work and run the page in the browser: a great Friday message should be there to greet you. Keep changing weekday and make sure the alert box displays the appropriate message each time.

Summary

Now you know how to write scripts that implement different actions on the basis of different conditions. Well done!

Keep experimenting with all the tools you've learned so far. If you have doubts, drop a line in the forum dedicated to this tutorial. When you're ready, move on to the next big topic: loops.


Related topics in the RepliesViews
No related topics yet

+ Post a new topic


<< Lesson 5: Smarter Scripts with Operators

Lesson 7: Leave Boring Repetitive Stuff to JavaScript with Loops >>