In JavaScript, there are two types of comparison operators:
This category includes all of the commonly known comparison operators (e.g., less-than, greater-than, equal-to, etc.). These are known as type-converting because, in case of a comparison between operands of different types, one of the operands is first converted to the other type and then the comparison is made.
function check(){
if(5 <= '5.01')
return true;
else
return false;
}
The function check()
, in the code snippet above, will return true
. This is because '5'
, which is a String
, is converted into a Number
before comparison. Therefore, we use the type-converting operators when the main thing to compare is the value, not the type, of the two operands.
function check (){ if("100" > 20) return true; else return false; } console.log(check());
When comparing two Objects, all relational operators, except for the ==
operator, use the valueOf()
method to convert the Objects into a suitable value for comparison. The ==
operator will only return true
when both the Objects are same; i.e., the reference variables point to the same JavaScript Object:
function compare1 (a, b){ if(a == b) console.log(a.name + " and " + b.name + " are equal"); else console.log(a.name + " is not equal to " + b.name); } function compare2 (a, b){ if(a <= b) console.log(a.name + " is less than or equal to " + b.name); else console.log(a.name + " is greater than " + b.name); } function Person(i, n){ this.id = i; this.name = n; } Person.prototype.valueOf = function(){ return this.id; } p = new Person(5, 'p'); q = new Person(5, 'q'); r = q; s = new Person(10, 's');; compare1(p, q); // Prints 'p is not equal to q'. compare1(q, r); // Prints 'q and q are equal'. compare2(r, s); // Prints 'q is less than or equal to s'.
In a strict comparison, true
is returned if, and only if, both the operands have the same type and value; moreover, in the case of JavaScript Objects, both should refer to the same Object.
The most commonly used strict comparison operators are the strict equality ===
and inequality !==
operators:
var compare1 = function(){ if(5 == '5') return true; else return false; } var compare2 = function(){ if(5 === '5') return true; else return false; } console.log(compare1()); // Type-converting console.log(compare2()); // Strict
RELATED TAGS
View all Courses