In this post we will continue to look at aspects of the BMI calculator script we have been creating, which should give you an example of JavaScript working in a real world application that could be integrated into a web design project.
If you have not already, take a look at the previous posts for the introduction and breakdown of the scripts:
JavaScript 101: Using Variables and Functions (Part 6.1)
JavaScript 101: Using Variables and Functions (Part 6.2)
This week we will explain the use of conditional statements to add logic in JavaScript. If you have not used them before they will add so much more power and flexibility to your scripts.
A conditional script is a way of asking the script to preform one task, if one condition is true, and then another if not. A conditional statement looks like this:
if(3<2) { //your script here } else if(3<3) { // your script here } else { // your script here }
As you can see above we have a structure in which the script runs down asking if one thing is true – run this, if not – move on.
The statements within the brackets are the conditions the script checks, in this case “3<2″. The symbol in the middle is what we call an operator, in this case the symbol means “is smaller than”. Lets take a look at the other operators:
> | Greater than |
< | Less Than |
>= | Greater or Equal To |
<= | Less Than or Equal To |
== | Equal To |
!= | Not Equal To |
The use of these operators within your script, along with the if/else statements, add a huge amount of power to your script allowing you to compare user entered variables, x/y co-ordinates of an object on the screen, or we could check the site referrer and display different results or redirect, accordingly. There is so much you can do when adding this aspect to your scripts, you just have to be creative.
Take a look back at the previous two posts and look at the Script for the BMI calculator, which should now make a lot more sense.
03:15 25/05/2011
very basic but helpful js tips, thank you very much for sharing.