Reputation: 586
EDIT: I will rephrase my question, I type Number < String and it returns true, also works when I do typeof(2) < typeof("2").
Number < String => true
typeof(2) < typeof("2") => true
I'm guessing it is the value of ASCII characters of each letter in Number and String but I am not sure if that is the reason this is returning true, and I want to know why does this happens, what processes or how does the interpreter gets to this result?
Upvotes: 2
Views: 153
Reputation: 14668
First answer:
The charCodeAt() method returns the numeric Unicode value of the character at the given index. Read here
Now if you do not specify any index position then character at 0th index is considered. Now, S
ASCII value is 83
and N
ASCII value is 78
. so, you are getting those number. Check here.
And 78 < 83 => true
is obvious.
Try "String".charCodeAt(1)
and you will get 116
which is ASCII value of t
Frankly speaking your comparison Number < String
is "technically" incorrect because Less-than Operator <
or any similar operator is for expressions, and Number
and String
are functions and not expressions. However @Pointy explained on how Number < String
worked and gave you results.
Comparison operators like <
works on expressions, read here. Typically, you should have a valid expression or resolved value for RHS and LHS.
Now this is the definition of expression, read more here - "An expression is any valid unit of code that resolves to a value. Conceptually, there are two types of expressions: those that assign a value to a variable and those that simply have a value."
So, (x = 7) < (x = 2)
or new Number() < new String()
is a "technically" valid/good comparison, even this Object.toString < Number.toString()
but really not Object < Function
.
Below are rules/features for comparisons, read more here
Upvotes: 5
Reputation: 21
JavaScript does the following thing:
"String".charCodeAt(); => 83
"S".charCodeAt(); => 83
"String".charCodeAt(0); => 83
The method charCodeAt(a) gets the char code from position a. The default value is 0
If you compare N > S you will get 78 > 83 => true
For the complete String Javascript calculates the sum of all ASCII char codes. So I can answer your question with yes.
Upvotes: 1
Reputation: 413996
The result of
Number < String
is not the result of comparing the strings "Number" and "String", or not exactly that. It's the result of comparing the strings returned from Number.toString()
and String.toString()
. Those strings will (in all the runtimes I know of) have more stuff in them than just the strings "Number" and "String", but those two substrings will be the first place that they're different.
You can see what those actual strings are by typing
Number.toString()
in your browser console.
Upvotes: 4