|
Free
Javascript
Tutorials
|
|
|
JavaScript Tutorials Javascript Operators |
||||||||||||||||||||||
|
The Operators, And, Or
Notice in that last code that the second age test uses the Greater Than symbol ( > ). Try entering the number 16 in your text box, and then click your button. What happened? If you haven't added the final else statement, then nothing will happen. This is because we're testing for Less Than 16 in the first if statement, and then testing for Greater Than 16 in the first else statement. We're not testing for exactly 16. So none of our statements will be true. What we need is another of our symbols. Either >= (Greater Than or Equal to) or <= (Less Than or Equal to). So, change your code. Take out either the Less Than symbol ( < ) or the Greater Than symbol ( > ). In it's place, insert either <= or >= to see what happens. Play about with the symbols to see how they work. What happens if you put both in? Like this: if (age <= 16) { alert("How's school these days?") } alert("It's tough being an adult") } alert("Please try again") }
ExerciseAdd a few more else if statements, and test for these ages groups: 17 to 25 Add a suitable alert message for when the command button is clicked. With an exercise like the one above, it's really handy to use the AND operator (&&) and the OR operator ( || ). Here's how to use them.
AND and ORThese two operators will return a Boolean value. You use them when
you want to test two or more conditions. For example, if you wanted
to test if someone was over 65 and had a buss pass, use AND; if you
wanted to test if someone was over 65 or had a buss pass, use OR. Like
this: if (Age >= 65 && BusPass == false) { alert("Pensioners - Get your free bus pass now!") } If BOTH conditions are true then the IF Statement is true. If just one of them is false, then the entire IF Statement is false. Note the format (and where the round brackets are): if (condition1 && condition2) { Code if true here } Contrast that with the OR operator: if (Age >= 65 || BusPass == false) { alert("Pensioners - Get your free bus pass now!") } This time, if just one of your conditions is true then the entire IF statement is true. They both need to be false for the entire IF Statement to be false. The format (syntax) is the same, except for the two pipe characters ( || ) in place of the two ampersands (&&).
Not a Number
|