The second group of possible comparisons in JavaScript (after equality operators), relational operators determine if one operand is greater or less than another. As such, they are frequently used in mathematical expressions, often in the form of comparing variables within if
statements.
Greater than operator
Determines if the left operand is greater than the right operand. In the console:
5 > 3
> true
These operators are almost always used to compare numbers, but they can also be used with strings. When this occurs, the Unicode value of the characters in each of the strings is added together and compared:
"Kirk" > "Picard"
> false
This can lead to very confusing results, and, as such, relational comparison of strings should be generally avoided.
Less than operator
Determines if the left operand is less than the right operand:
var romeFounded = -753;
var beijingFounded = -1100;
beijingFounded < romeFounded;
> true
Greater than or equal to operator
Tests if the first operand is greater than or equal to the second operand:
var highScore = 1100;
var userScore = 700;
var message = "";
if (userscore >= highScore) {
message = "We have a new winner!";
} else {
message = "Sorry, you haven't beaten or equalled the high score.";
}
Less than or equal to operator
Tests if the first operand is less than or equal to the second operand:
11003 <= 2
> false
Not Equal To?
Sometimes new coders will try to use <>
as a way to express “not equal to” in JavaScript. Unfortunately, that isn’t supported; use the inequality or (preferably) the strict inequality operators instead.
Photograph by Stephen Poff, licensed under Creative Commons
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.