Comparison's in JavaScript
-
I would expect the following two expressions to both evaluate to false: 2 < "12" "2" < "12" The second one returns false. That makes sense to me "1" is before "2". In the first case, we are comparing a number with a string. I would expect the number 1 to be converted to the string "1" and therefore to evaluate to false. However, it is evaluating to true. What am I missing? Thanks, Bob
-
I would expect the following two expressions to both evaluate to false: 2 < "12" "2" < "12" The second one returns false. That makes sense to me "1" is before "2". In the first case, we are comparing a number with a string. I would expect the number 1 to be converted to the string "1" and therefore to evaluate to false. However, it is evaluating to true. What am I missing? Thanks, Bob
BobInNJ wrote:
it is evaluating to true
BobInNJ wrote:
2 < "12"
12 is getting converted to int.
Social Media - A platform that makes it easier for the crazies to find each other. Everyone is born right handed. Only the strongest overcome it. Fight for left-handed rights and hand equality.
-
I would expect the following two expressions to both evaluate to false: 2 < "12" "2" < "12" The second one returns false. That makes sense to me "1" is before "2". In the first case, we are comparing a number with a string. I would expect the number 1 to be converted to the string "1" and therefore to evaluate to false. However, it is evaluating to true. What am I missing? Thanks, Bob
Comparing data of different types may give unexpected results. When comparing a string with a number, JavaScript will convert the string to a number when doing the comparison. When comparing two strings, "2" will be greater than "12", because (alphabetically) 1 is less than 2.