What Happens When You Compare Strings and Numbers and Understanding JavaScript Type Conversion in Comparisons with Real Examples.

What Happens When You Compare Strings and Numbers and Understanding JavaScript Type Conversion in Comparisons with Real Examples.

Our Javascript Code:

console.log("2" > "10"); console.log("2" > 10);

1. First Line

console.log("2" > "10");
  • 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 10 is "bigger" than 2 mathematically because it is comparing strings alphabetically, not numbers!


2. Second Line

console.log("2" > 10);
  • Here, "2" is a string, but 10 is 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" becomes 2 (a number), and then it compares:

        2 > 10
  • 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.


Post a Comment

Previous Post Next Post