JavaScript “Light Bulb” Moments: Tricky Comparison

How can “55” be less than “6” in Javascript?

Abhay Srivastav
Bits and Pieces

--

I promise….

Introduction

I was recently debugging a strange issue in javascript which was somehow always happening for 2 digits numbers.

This short post is the outcome of the learning process I went through in that debugging.

I’ll start with a bit of code.

"7" > "6" - true
"55" > "6" - false

So the first one makes sense.

But, how come “55” is lesser than “6” in Javascript? Strange, right?

I had the exact same reaction the first time this happened to me.

Then, I decided to dig deeper and understand the reason for this behavior, diving into how comparison really works in JavaScript.

How does comparison work in JavaScript?

When you compare a string and a number, both will be converted to numbers and then compared.

"55" > 6 - true

The above code makes sense, since both are converted to numbers, then compared.

When you compare a string to a string, then the comparison is done character by character, meaning first character is compared to the first character of second character and so on.

"a" > "b" - false
"d" > "c" - true

Since strings are compared in lexicological order, the above expressions make sense.

Back to “55 > “6”

Now back to our actual problem statement.

We are comparing a string to another string, and string comparison is done character by character which happens as below.

"55" > "6"First character of "55" is lesser than first character of "6", hence false"55" > "51"
First character of "55" and "51" are equal, then we move on to the second character, i.e. "5" and "1", since "5" > "1", hence we have true

Conclusion

To avoid such glitches, whenever we are comparing numbers, we should always convert it into numbers first.

Number("55") > Number("6") - true

I hope it makes sense now.

Now to let you explore a bit more below are some statements.

Wonder what the results would be and why?

"a" > "b"
"a" > 5
5 > undefined

Thanks for reading :)

Do check out a youtube trim tool i created https://youtubecut.com

--

--