Why JavaScript Evaluates '2' > '10' as True: String vs Number Comparison
In JavaScript, comparing '2' and '10' as strings yields a surprising result of true, unlike the numeric comparison which correctly returns false. This happens because JavaScript uses lexicographical ordering when comparing string values, evaluating characters one by one as in a dictionary. Since the character '2' ranks higher than '1' in character ordering, '2' is considered greater than '10' as strings. When one value is a string and the other a number, JavaScript automatically converts the string to a number before comparing, restoring expected mathematical behavior. The key takeaway for developers is that data types fundamentally affect how comparisons are evaluated in JavaScript.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in