Relational operators perform comparisons between values.
The Relational Operators in Javascript are listed as follows.
<
>
<=
Special rules are as follows:
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);
var result1 = 5 > 3; //true
console.log(result1);/*from w ww .j ava 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.
The equal operator in Javascript is the double equal sign ==
.
The not-equal operator is !=
.
They both do conversions to determine if two operands are equal as follows.
The following example lists some special cases and their results:
console.log(6 == 6); //true
console.log("6" == 6); //true
console.log(null == undefined); //true
console.log("NaN" == NaN); //false
console.log(6 == NaN); //false
console.log(NaN == NaN); //false
console.log(NaN != NaN); //true
console.log(false == 0); //true
console.log(true == 1); //true
console.log(true == 2); //false
console.log(undefined == 0); //false
console.log(null == 0); //false
/* ww w. ja v a2s .c o m*/
The code above generates the following result.
The identically equal operator is ===
and returns true only if the operands are equal without conversion.
The not identically equal operator is !==
and returns true only if the operands are not equal without conversion.
var result1 = ("5" == 5); //true - equal because of conversion
console.log(result1);
var result2 = ("5" === 5); //false - not equal because different data types
console.log(result2);
result1 = ("5" != 5); //false - equal because of conversion
console.log(result1);
result2 = ("5" !== 5); //true - not equal because different data types
console.log(result2);
The code above generates the following result.
null === undefined
is false because they are not the same type.
It is recommended to use identically equal and not identically equal to maintain data type integrity.
The conditional operator has the following form:
variable = boolean_expression ? true_value : false_value;
If boolean_expression is true, then true_value is assigned to the variable
.
If boolean_expression is false, then false_value is assigned to the variable
.
var num1 = 1;
var num2 = 2;
var max = (num1 > num2) ? num1 : num2;
console.log(max);
The code above generates the following result.