
Javascript
Tutorial: Testing and Comparing Variables
Home > Build
> Programming > Javascript
> Javascript Tutorial
by
Boris Mordkovich
THE
if KEYWORD
The if
keyword is one that you will use over and over again in Javascript. It is used
to test and/or compare a variable. Lets get to the example.
var
name = 'John';
if (name == 'Bob')
I admit, this isn't a very practical use for the script.
The statement is basically saying if name equals Bob write Bob Curtis. But analyze
the parts of the script, the name variable, the if keyword, the parentheses, the
variable to be tested (name) the == operator, the string used to test the variable,
and what to do if the statement is true.
OPERATORS
Operators
are used to compare variables (such as the == operator above); they consist of
two groups, conditional and logical.
Conditional
Conditional
operators are the syntax used to compare the two variables.
| == | is
equal to |
| != | is
not equal to |
| < | is
less than |
| <= | is
less than or equal to |
| > | is
greater than |
| >= | is
greater than or equal to |
Logical
Logical
operators are the operators you use if you want to compare more than two variables.
Just to give you an idea
of how logical operators work, check out the syntax below.
THE else KEYWORD
If you are using several if statements to test the same
variable and you want to include a choice that will be executed if none of the
previous statements are true, you should use the else keyword.
if
(name == 'Bob')
else
if (name == 'Sue')
else
The above statements would check to see
if name equalled Bob and because it didn't it checked
to see if name equalled Sue, if it reaches the else
keyword and none of the above if statements have been true Javascript executes
whatever is after the else keyword.