The relational operators are part of the comparison operators.
There are four relational operators; these are less-than ("<"), greater-than (">"), less-than-or-equal-to ("<=") and greater-than-or-equal-to (">="). These operators work with two values that don't necessarily have to be numbers, in which case they are converted to numbers behind the scene.
The result of a relational comparison is always a Boolean value (true, false).
Example:
var result = 5 < 24; //false
These are the rules that relational operators follow:
- If the operands are number, regular numerical operation is performed;
- If the operands are strings, the character codes of each are compared;
- If one operand is a number, the other is converted into a number and regular operation is performed;
- If an operand is an object, or a "Boolean, it will be converted into a number, and proceed as regular numerical operation.
When comparing the string types, a capital letters matter. That is because the character codes of uppercase letters are all lower than those of lowercase, for instance:
var res = "House" < "javascript"; //true
var res = "house" < "javascript"; //false
To be sure that a correct operation is performed, the best technique is to convert all the letters into lowercase by using method .toLowerCase(), as seen here:
var res = "House".toLowerCase() < "javascript".toLowerCase(); //false
var res = "5" < 12; //false
In some cases number strings cannot be meaningfully converted to real numbers and they become NaN, as show here:
var res = "b" < 5; // false
var res = "b" > 5; // false
As seen above, the result is always false because the letter "b" cannot be compared to a number in a meaningful way.
Example
The example with relational (comparison) operators in JavaScript:
Comments
No comments have been made yet.
Please login to leave a comment. Login now