O'Reilly logo

Learning JavaScript by Shelley Powers

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The Conditional Operators

The conditional operators are a way of testing for specific conditions: equality, identity, relational, and logical. Though the processes may differ, and they range from simple to complex, the result of using such operators is one of two values: true or false.

The Equality and the Identity (String Equality) Operators

One of the most common operators used in a conditional expression is the equality operator, ==. It is used when a variable is compared with another variable or literal value, and based on the result, an action or set of actions is triggered:

// at some point  in application, assign 3 to variable nValue
var nValue = 3;
...
if (nValue == 3) ...

In this example, if the variable nValue is equal to 3, what follows (represented by the ellipses in the text) is processed. Otherwise, the flow of the program skips over the code block and goes to the first statement following.

Warning

Be careful not to leave off the second equals sign (=). If you do, the expression becomes one of assignment, not conditional testing. The variable nValue is assigned the value of 3. Since the assignment was successful, it returns true. It always returns true. A JavaScript error doesn’t occur, and as such, it may be hard to spot this error in debugging.

As with the addition operator, the equality operator converts the variable’s data type to facilitate the evaluation of the expression. If one value is numeric and the other is string, comparing both is successful if the value is ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required