Comparison Operators

In the previous reading of the boolean data type, booleans were described as a way to represent the validity of an expression. You'll continue this conversation by exploring comparison operators. As you learn about these operators, bear in mind that all comparisons will result in a boolean, true or false.

When you finish this article, you should be able to:

The relative comparators

Using these operators is pretty straightforward. Here are a few examples:

console.log(10 > 5);  // => true
console.log(10 < 5);  // => false
console.log(1 < 7);   // => true
console.log(7 <= 7);  // => true
console.log(5 === 6); // => false
console.log(5 !== 6); // => true

console.log("a" === "a"); // => true
console.log("a" === "A"); // => false

console.log(false === false);        // => true
console.log(true && false === true); // => false
    

Notice that a comparison expression always evaluates to a boolean value (true or false). Comparison operators like === are useful to compare strings, booleans, etc., not just numbers.

Did you know? 'a' < 'b' is valid JS code? When you relatively compare strings using > or < you will be comparing them lexicographically. Lexicographically is fancy shmancy talk for "dictionary" order! A "lesser" string is one that would appear earlier in the dictionary:

console.log("a" < "b");             // => true
console.log("apple" < "abacus");    // => false
console.log("app" < "apple");       // => true
console.log("zoo" > "mississippi"); // => true
    

Gotcha! Capitalized letters are considered lexicographically less than lower case letters. i.e "A" < "z" // => true.

=== vs ==

In JavaScript there are two equality operators triple-equals (===) and double-equals (==). The operators differ in how they compare across differing types. Triple-equals performs strict equality, meaning it will return true only if the types--and values, of course--are the same. Double-equals performs loose equality, meaning it can return true even if the values are of different types. Double-equals may coerce a value into another type for the comparison, but this behavior is hard to predict:

console.log(5 === "5");   // false
console.log(5 == "5");    // true
console.log(0 === false); // false
console.log(0 == false);  // true
    

Whoa! Surprised by these results? It can be hard to predict how == behaves, so avoid using it in this course and as a best practice. Stick to using === because it respects data types.

What you've learned