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 ...

Get Learning JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.