Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 156 ยท Data Types

Type Conversion and Coercion

Learn how JavaScript converts values between strings, numbers and booleans, both explicitly and through implicit coercion, and avoid the classic == surprises.

Values in JavaScript often need to change type. Text typed into a form arrives as a string, but you want to add it up as a number. A number needs to go into a message as text. Any value can end up in an if, which needs a boolean.

There are two ways this happens. Explicit conversion is when you ask for it, with functions like Number() or String(). Implicit coercion is when JavaScript converts a value on its own because an operator needs a different type. Coercion is what makes "5" * 2 equal 10 but "5" + 2 equal "52". This lesson teaches the rules behind both, so the surprises stop being surprises.

Converting to a string

String(value) turns any value into text. The results are mostly what you'd expect:

JS String() conversions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

String() is the safest choice because it works on everything. The .toString() method gives the same result for most values, but calling it on null or undefined throws a TypeError โ€” they have no methods.

Converting to a number

Number(value) converts to a number, and returns NaN ("not a number") when it can't make sense of the input:

JS Number() conversions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The rules worth memorizing:

  • Strings: surrounding whitespace is ignored; an empty (or all-space) string becomes 0; anything that isn't a valid number literal becomes NaN.
  • Booleans: true โ†’ 1, false โ†’ 0.
  • null โ†’ 0, but undefined โ†’ NaN.
  • Objects and arrays are first turned into a primitive (usually a string), then converted. That's why [] (โ†’ "" โ†’ 0) and [7] (โ†’ "7" โ†’ 7) behave so oddly.

parseInt and parseFloat

Number() is strict: one stray character and you get NaN. The parseInt() and parseFloat() functions from Numbers are lenient instead โ€” they read from the start of the string and stop at the first character that doesn't fit:

JavaScript
Number("12px");        // NaN
parseInt("12px", 10);  // 12
parseFloat("1.5rem");  // 1.5
parseInt("px12", 10);  // NaN โ€” must start with a digit
Number("");            // 0
parseInt("", 10);      // NaN

Use Number() when the whole string should be a number, such as validating input. Use parseInt/parseFloat to pull a number out of the front of a string such as a CSS value. Always pass 10 as the second argument to parseInt to be explicit about decimal.

You'll also see the unary plus, +value, used as a short form of Number(value): +"42" is 42. It works the same way but is easy to overlook when reading code.

Converting to a boolean

Boolean(value) follows the truthiness rules from Booleans and Truthiness: the falsy values false, 0, -0, 0n, "", null, undefined and NaN become false; everything else becomes true.

JavaScript
Boolean("0");   // true  โ€” non-empty string
Boolean(0);     // false
Boolean([]);    // true  โ€” every object

Implicit coercion

Now the interesting part: operators that convert values on their own.

The + operator prefers strings

+ does two jobs: adding numbers and joining strings. If either side is a string (after objects are turned into primitives), it joins. Otherwise it adds. All the other arithmetic operators (-, *, /, %, **) only do math, so they always convert to numbers:

JS + versus the other operators

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last two lines show the bug you'll meet most in practice. Values from form fields, URLs and prompt() are always strings. Convert them explicitly before doing math.

Conditions and logical operators

if, while, ? :, !, && and || coerce to boolean using truthiness. That's the "good" coercion โ€” predictable and widely used.

Comparisons with < and >

Relational operators convert to numbers, unless both sides are strings, in which case they compare the text character by character:

JavaScript
"10" < 9;     // false โ€” "10" becomes 10
"10" < "9";   // true  โ€” text comparison: "1" comes before "9"

Sorting numbers stored as strings is a classic source of this bug. More in Comparison and Equality.

The == surprises

The loose equality operator == converts its operands before comparing, using a set of rules that produce some infamous results:

JS Loose equality in action

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Roughly, == works like this: null and undefined equal each other and nothing else; booleans are converted to numbers; when a string meets a number, the string becomes a number; objects are turned into primitives. Chaining those steps gives results like [] == false ([] โ†’ "" โ†’ 0, and false โ†’ 0).

You don't need to memorize the full algorithm. The professional habit is simple:

Use === and !== by default. They compare without converting, so "5" === 5 is simply false. Convert values explicitly first if their types might differ. The one common exception is value == null, which deliberately checks for both null and undefined.

Explicit beats implicit

Coercion is part of the language and you'll use the friendly parts every day โ€” truthiness in if, numbers inside template literals. But when a conversion matters to your logic, write it out:

JS Making conversions visible

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the multiplication happened to give the right answer โ€” * converts both strings to numbers โ€” while + silently produced "34.50". Code that "works by accident" like this is fragile: change one operator during a refactor and the bug appears. Converting once, right where the data enters your program, means everything after that point can trust its types.

Explicit code tells the next reader (often you, months later) exactly what types you expect, and it gives you a natural place to check for NaN.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the result of "7" + 3?

    When either side of + is a string, + joins text, so 3 becomes "3".
  2. 2. What is the result of "7" - 3?

    - only does math, so the string is converted to the number 7.
  3. 3. Which conversion returns NaN?

    undefined becomes NaN. The empty string, null and false all become 0.
  4. 4. You need to read "24px" and get the number 24. Which works?

    parseInt reads digits from the start and stops at p. Number() and unary + require the whole string to be numeric.
  5. 5. Why is === recommended over ==?

    == applies coercion rules with surprising results; === requires the same type and value. == isn't deprecated, just error-prone.

Summary

  • Convert explicitly with String(), Number() and Boolean(); parseInt/parseFloat read a number from the start of a string.
  • Number("") and Number(null) are 0; Number(undefined) and invalid strings give NaN.
  • + joins strings if either side is a string; -, *, /, % and ** always convert to numbers.
  • Form and URL values are strings โ€” convert them before doing math.
  • == coerces with surprising rules; use === and convert explicitly instead.

Next: BigInt and Symbol โ€” the two remaining primitive types: huge integers and unique keys.