Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Number < String returns true in JavaScript?

Tags:

javascript

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?

like image 510
Santiago Suárez Avatar asked Sep 16 '26 13:09

Santiago Suárez


1 Answers

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


Second answer based on OP's edited question:

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.

More insight on comparison operators

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

  • Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
  • Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another.
  • Two Boolean operands are strictly equal if both are true or both are false.
  • Two distinct objects are never equal for either strict or abstract comparisons.
  • An expression comparing Objects is only true if the operands reference the same Object.
  • Null and Undefined Types are strictly equal to themselves and abstractly equal to each other.
like image 180
hagrawal Avatar answered Sep 18 '26 03:09

hagrawal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!