Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Comparison

A comparison answers a yes-or-no question: is the order total over a hundred dollars, does the password match, is the user 18 yet. The result of a comparison is always a boolean, true or false.

Comparison operators

The simplest comparison is "greater than":

console.log(5 > 3); // true
OperatorMeaningExampleResult
>greater than5 > 3true
<less than5 < 3false
>=greater than or equal5 >= 5true
<=less than or equal4 <= 3false
===equal5 === 5true
!==not equal5 !== 3true

Strict equality

The === operator checks that the values match and have the same type. So the number 5 and the string '5' are not equal:

console.log(5 === '5'); // false

Note that equality is written with three = signs. A single = is assignment, not comparison.

Loose equality

JavaScript also has the old == operator. Before comparing, it converts the values to one type, which gives surprising results:

console.log('5' == 5); // true
console.log(0 == '');  // true

Because of such surprises, modern code uses only === and !==. The == and != pair shows up mostly in old programs.

Storing the result

A comparison is an ordinary expression, and its result can go into a variable. Such variables are usually named starting with is or has:

const age = 20;
const isAdult = age >= 18;
 
console.log(isAdult); // true

Such a variable is then used in conditions — that is the next chapter.

Comparing strings

Strings are compared character by character, alphabetically: a letter further along in the alphabet counts as "greater". Capital letters are less than lowercase ones:

console.log('cat' > 'car');      // true
console.log('Anna' === 'anna'); // false

To compare strings ignoring case, bring both to the same case: a.toLowerCase() === b.toLowerCase().

NaN equals nothing

The special value NaN is not equal to anything, not even itself. So the check x === NaN is always false:

console.log(NaN === NaN);       // false
console.log(Number.isNaN(NaN)); // true

To check for NaN, use the Number.isNaN() function.

Common mistake

Numbers written as strings are compared as text — by the first character, not by size. The character '1' is less than '9', so '10' turns out to be less than '9':

console.log('10' < '9');                 // true
console.log(Number('10') < Number('9')); // false

Values from forms and files arrive as strings, so convert them to numbers before comparing.

Thanks for reading!

Donate to the site — we work hard for you.