How to use Relational Operators in Javascript
Description
Relational operators perform comparisons between values.
The Relational Operators in Javascript are listed as follows.
- less-than
<
- greater-than
>
- less-than-or-equal-to
<=
- greater-than-or-equal-to >=
Special rules
Special rules are as follows:
- If the operands are numbers, perform a numeric comparison.
- If the operands are strings, compare the character codes of each corresponding character in the string.
- If one operand is a number, convert the other operand to a number and perform a numeric comparison.
- If an operand is an object, call valueOf() and use its result to perform the comparison.
- If valueOf() is not available, call toString() and use that value.
- If an operand is a Boolean, convert it to a number and perform the comparison.
Example
Character codes of uppercase letters are lower than the character codes of lowercase letters.
var result = "B" < "a"; //true
console.log(result);
result = "B".toLowerCase() < "a".toLowerCase(); //false
console.log(result);
In the following code both operands are strings, they are compared by their character codes).
var result = "23" < "3"; //true
console.log(result);
In the following code the string "23" is converted into the number 23 and then compared to 3.
var result = "23" < 3; //false
console.log(result);
Example 2
var result1 = 5 > 3; //true
console.log(result1);/*from w w w. ja va 2s. c om*/
result2 = 5 < 3; //false
console.log(result2);
result = "a" < 3; //because "a" becomes NaN
console.log(result);
result1 = NaN < 3; //false
console.log(result1);
result2 = NaN >= 3; //false
console.log(result2);
The code above generates the following result.