Skip to the page

Values, types and coercion · mid

Numbers, precision, BigInt and string comparison

Every JavaScript number is a 64-bit floating-point value, so 0.1 + 0.2 is not exactly 0.3 and integers are only safe up to 2^53 − 1; strings are sequences of UTF-16 code units and compare code unit by code unit.

The notes

What you must know

  • Numbers are IEEE 754 doubles: 0.1 + 0.2 is 0.30000000000000004. Compare floats with a tolerance (Math.abs(a - b) < Number.EPSILON) or keep money in integers (paise, not rupees).
  • Number.MAX_SAFE_INTEGER is 2^53 − 1 = 9007199254740991. Bigger IDs from an API lose precision when parsed as numbers: send them as strings, or use BigInt (10n).
  • BigInt and Number can't be mixed in arithmetic (1n + 1 throws TypeError), and JSON.stringify throws on BigInt.
  • NaN is the only value not equal to itself. Number.isNaN(x) checks for the real NaN; the global isNaN(x) converts first, so isNaN('abc') is true.
  • Number('12px') is NaN (the whole string must be numeric); parseInt('12px') is 12 (stops at the first bad character). Always pass a radix: parseInt(s, 10). parseInt(0.0000005) is 5 because the number becomes the string '5e-7'.
  • String < and > compare UTF-16 code units from left to right: 'apple' < 'pineapple' because 'a' (97) < 'p' (112), 'Z' (90) < 'a' (97), and '10' < '9'. Use localeCompare or Intl.Collator for user-facing sorting.
  • '😀'.length is 2 because the emoji uses two UTF-16 code units. [...str] splits by code points; Intl.Segmenter splits by user-visible characters. codePointAt vs charCodeAt.
  • Tagged templates (taga${x}b) receive the string parts and the values separately. Libraries such as styled-components and GraphQL's gql use them.

The red pen

Common traps: mistake → fix

  • Mistake: 0.1 + 0.2 === 0.3 is true

    Fix: it is false because of floating-point rounding.

  • Mistake: parseInt and Number do the same thing

    Fix: parseInt stops at the first invalid character and needs a radix; Number rejects the whole string.

  • Mistake: String comparison is dictionary order

    Fix: it is code-unit order, so uppercase comes before lowercase and '10' < '9'.

  • Mistake: str.length counts characters

    Fix: it counts UTF-16 code units; many emoji count as 2 or more.

Easy to hard

Questions interviewers ask, easy to hard

  1. Why is 0.1 + 0.2 !== 0.3? How do you handle money in a checkout?
  2. What is Number.MAX_SAFE_INTEGER, and how can a large order ID from an API break?
  3. Explain why 'apple' > 'pineapple' is false. How do you get a character's code? (Flipkart, 2025)
  4. Why is '😀'.length 2? How do you count characters the user sees?
  5. When would you use BigInt, and what are its limits?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview