Learn Modern Unobtrusive JavaScript
Testing Conditions
Apart from deciding when to run what JavaScript code based on when the appropriate events occur, JavaScript also needs to be able to make decisions on what code that it runs during processing. You may want the code to do different things depending on the value that a given field has or perhaps based on whether or not something exists.
JavaScript provide two ways of being able to test conditions to determine whether or not specific code should be run. These two methods are the if statement and the switchstatement. Let's start by looking at the if statement. Here is an example.
if ('Stephen' === name) {
message = "Welcome back Stephen";
} else {
message = "Welcome " + name;
}
An if statement starts with the word if followed by the condition to test enclosed in (). The code to run if the condition is true then follows enclosed in {} (the { and } can be omitted if there is only one statement. Where you have alternative code to run when the condition is false then the true code is followed by the word elseand then the code to run when it is false again enclosed in {}.
most condition checks are done by comparing two values to see if one is equal to, not equal to, greater or less than the other. Here is a list of the comparison operators that we can use in these condition tests.
== equal values but not necessarily the same type eg. 3 == '3'
=== equal value and the same type
!= not equal values
!== not equal values or are different types
< less than
<= less than or equal
> greater than
>= greater than or equal
For less than and greater than comparisons involving text strings (enclosed in '' or "") rather than numbers the comparisons are based on the order in which the characters appear in the ASCII characterset (this means that numbers are less than all uppercase letters which are all less than lowercase letters so 9 < 'A' < 'Z' < 'a').
If statements can be made a lot more complex than this with nesting and testing multiple conditions at once but we'll look further into that in a later tutorial.
The switch statement only permits you to test one field for being equal to specific values. Where it differs from the if statement is that you are not limited to testing if the field is equal to one value. A switch statement can test for any number of different values and perform different processing depending on which value the field holds.
switch (letter) { case 'a': a += 1; break;
case 'b': b += 1; break;
case 'c': c += 1; break;
case 'd': d += 1; break;
case 'e': e += 1; break;
case 'f': f += 1; break;
default: otherLetter += 1;
}
In this example our switch statement runs different code when the value of letter is 'a', 'b', 'c', 'd', 'e', or 'f' as well as having yet another default piece of code to run if the field cantains anything other than those six specific values.
No comments:
Post a Comment