Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Basics (Retired) Making Decisions with Conditional Statements Combining Multiple Tests Into a Single Condition

Charlotte Zhang
Charlotte Zhang
4,425 Points

Guys, I am a little bit confused about the comparison between number and strings.

When we studies comparison operator, the instructor said that "letter strings will always come after number strings, if you compare a number and a letter, a number is less than a letter". But here, he is saying that you can't make comparison between number and string/letter. I am a bit confused. Please help me.

3 Answers

andren
andren
28,558 Points

What he meant is that if you store a number in a string and compare it to a letter, for example something like this:

'A' > '1' // True, since 'A' is considered greater than '1'

Then the string with the number will be considered to be lesser than the string with a letter. But in that case you are not comparing a string and a number, but two strings. If you compare a string and a number like this:

'A' > 1 // False, since strings can't be compared to numbers

Then the comparison won't work.

The important thing to understand is that a string and a number is classified as different types of data in JavaScript, and have different rules surrounding their use. And anything enclosed in single or double quotes is considered a string, even if it only contains a number.

Terrance Corley
Terrance Corley
11,990 Points

Hi Charlotte,

Andren pretty much hit the nail on the head. It's also good to keep in mind the difference between...

'7' == 7

and

'7' === 7

The first example with the double equal sign comparison operator will compare only the values, so this example renders true.

The second example however is more strict and the triple equal sign comparison operator will compare both the values and the value types, so this example will render false because one is a string and one is a number.

Hope this helps.

Sooo yehh conclusion is anything in strings are characters and not a number. '7' = character 7. 7 = number 7. like 'A' is more than 'B' and 'C', '7' is lower than 'A', 'B' and 'C'. Just like the character 'A' is lower than 'a' in other means its table of characters and no relationship with numbers bluntly. So if you compare the character with the number there will be mistakes.