Our Javascript Code:
1. First Line
- Both "2" and "10" are strings. (Because they are inside quotes
"...", they are treated as text, not numbers.) - When you compare two strings using
>, JavaScript does NOT convert them to numbers automatically. - Instead, it compares them alphabetically, character by character, just like in a dictionary!
So how does it compare "2" and "10"?
- First, it looks at the first character of each string.
- In
"2", the first (and only) character is'2'. - In
"10", the first character is'1'. -
It compares
'2'and'1'. - Now remember: in Unicode/ASCII order, ASCII code of
'2' is 50 and'1' is 49.
✅ So 50 > 49 is true!
Important note: It doesn’t care that
10is "bigger" than2mathematically because it is comparing strings alphabetically, not numbers!
2. Second Line
-
Here,
"2"is a string, but10is a number. - When you compare a string and a number, JavaScript automatically converts the string to a number (this is called type coercion).
- So
"2"becomes2(a number), and then it compares:
- And obviously, 2 is not greater than 10, so:
It returns false.
✔ Final Answer:
A) true false
This question appeared in the Mindtree 2nd round of interview, testing the candidate’s knowledge of comparisons operator between string and number when we declare a variable using var keyword in JavaScript.
