How to Compare Strings Using the Greater Than and Less Than Comparison Operators in JavaScript (Easy!)

Okay, so far we’ve only compared numbers, but what about the letters of the alphabet?

Comparing strings in a word is very similar to how you would compare letters in the alphabet, but with a few differences.

How are letters of the alphabet prioritized in JavaScript when compared?

Uppercase letters are always less than lowercase letters in JavaScript.

Also, JavaScript reads the comparison from left to right, one by one.

Letters starting from the beginning of the alphabet like “a” are the lowest priority and they get higher as they move towards the letter “z.”

Example 1: Comparing strings to strings using the comparison operator

The way strings are ordered is pretty much alphabetic (with some minor exceptions).

Here’s a regular example:

console.log("Erin" > "Tracy");

The output:

false

What it’s asking here is if the word Erin is greater than the word Tracy.

That’s not true because T is greater than E according to the sorted order of the alphabet.

The letters become greater from left to right.

In order to make this true, you’d have to flip that greater than operator into a less than operator.

Let’s do another example.

Example 2: Comparing a capital letter to a lower case letter in JavaScript

So what’s the output if we were to test this:

console.log("Z" > "a");

So is capital “Z” really greater than the lowercase “a?”

The answer is:

false

Capital letters are always less than lowercase. Or, in other words, lowercase words are always greater than capital letters.

Leave a Comment