cf.completefrontendCode editorOpen lab
THE JAVASCRIPT FIELD GUIDE

Type conversion

Turn JavaScript values into strings, numbers, and booleans on purpose, and recognize the implicit conversions behind common surprises.

By the end you can
  • 01
    Choose the right translatorUse String(), Number(), and Boolean() deliberately.
  • 02
    Spot silent conversionsPredict when operators convert values for you.
  • 03
    Handle user input safelyConvert prompt or form text at the edge and check NaN.

Why conversion matters

JavaScript values have types. "25" is a string, 25 is a number, and true is a boolean. They can look similar on the page, but they behave differently when you do math, build messages, or make decisions.

Type conversion means turning a value from one type into another. Sometimes you ask for that conversion yourself. Sometimes JavaScript does it quietly because an operator needs a certain kind of value. This lesson is about knowing the difference.

The practical definition

Convert values when the next line needs a different type: use Number() for math, String() for display text, and Boolean() for a truthy/falsy decision.

Earlier lessons showed the mystery: "5" + 3 becomes "53", while "5" - 3 becomes 2. The Interaction lesson also warned that prompt() returns a string, so "25" + 1 becomes "251". By the end of this lesson, those results should feel predictable instead of random.

String(), Number() & Boolean(): three translators

INTERACTIVE

Think of String, Number, and Boolean as three translators. Each speaks one target language. Hand a value to the translator, and it gives you a value of that type.

Real-life analogyThree translators at a help desk

At an airport help desk, you choose the translator who speaks the language you need next. JavaScript is the same: choose the target type based on what the next operation needs.

In real life: The number translator
In JavaScript: Number(value): useful before arithmetic
In real life: The text translator
In JavaScript: String(value): useful before display
In real life: The yes/no translator
In JavaScript: Boolean(value): useful before a condition

Where the analogy stops: A human translator understands meaning. JavaScript’s translators follow fixed rules, so Boolean("false") is true because the string is not empty.

Try the playground. Type any text, or use the presets. The code stays the same; only the value on line 1 changes.

Converter playground
The checklistPop out in the code editor (opens in a new tab)JavaScript
const value = "42px";Number(value);parseFloat(value);+value;String(value);Boolean(value);Number.isNaN(Number(value));
Real results"42px"
Number(value)NaN

Converts the whole value to a number.

parseFloat(value)42

Reads a decimal number from the start of a string.

+valueNaN

A short form of Number(value).

String(value)"42px"

Makes text for display.

Boolean(value)true

Checks truthy or falsy.

Number.isNaN(Number(value))true

Use this after Number to catch failed conversions.

Try it yourself

Pick a preset or type any text. No arbitrary code is run.

Number needs the whole string to be numeric. parseFloat stops when the number part ends.

The playground runs fixed conversions against your text. It does not evaluate the text as JavaScript code.

Notice the big pattern: Number() wants the entire value to be numeric, so "42px" becomes NaN. parseFloat() is looser for strings: it reads the number from the start and stops at px. Unary plus, +value, is a short form of Number(value).

Explicit vs implicit conversion

SORT

Explicit conversion is conversion you can point to: the code names the target type. Number(input) says, “make a number here.” String(total) says, “make text here.”

Implicit conversion is conversion JavaScript performs while doing another job. "5" - 2 subtracts, so the string becomes a number silently. if (items.length) needs a yes/no decision, so the number becomes a boolean silently.

Real-life analogyThe currency-exchange booth

Explicit conversion is like walking to a currency-exchange booth and asking for a specific currency. Implicit conversion is like a shop that accepts your money and silently converts at its own rate: convenient, until the rate surprises you.

In real life: You visit the booth and ask for euros
In JavaScript: Explicit: Number(value) asks for a number
In real life: A shop accepts your cash and silently converts it
In JavaScript: Implicit: an operator converts while doing its own job
In real life: The posted rate is easy to check
In JavaScript: Named conversion is easier to review

Where the analogy stops: Currency exchange rates vary by place. JavaScript conversion rules are fixed by the language; the surprise comes from not noticing which rule was used.

Explicit or implicit?
  • Number(input)
  • "Total: " + price
  • if (items.length)
  • String(42)
  • score * "2"
  • !!value
Try it yourself
0 of 6 correct

Sort each snippet by whether it asks for conversion directly or lets JavaScript convert while doing something else.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Professional code still uses implicit conversion in common patterns, especially conditions. The rule of thumb is not “never implicit.” It is “be explicit at boundaries, especially when user input enters your program.”

Number conversion: useful, strict, and a little surprising

Number(value) is the safest first tool when you need a numeric value. It either gives you a number or the special value NaN, which means Not-a-Number. After converting, check with Number.isNaN(result).

What Number(value) returns
ValueResultWhy
""0Empty string becomes 0.
" 42 "42Whitespace is trimmed first.
"42px"NaNThe px makes the whole conversion fail.
"0x1A"26Hexadecimal notation is accepted.
"1e3"1000Scientific notation means 1 × 10³.
null0null becomes 0.
undefinedNaNundefined becomes NaN.
true1true becomes 1.
false0false becomes 0.
[]0An empty array stringifies to empty text, then 0.
[5]5A one-item array stringifies to "5".
[1, 2]NaN"1,2" is not a valid number.
{}NaNPlain objects become text that is not numeric.

The most practical surprise is blank text. Number("") and even Number(" \n ") return 0. JavaScript trims whitespace first; if nothing remains, it treats the result like zero. If blank input should be invalid, check value.trim() === "" before Number(value).

Number() vs parseFloat()

Number("42px") is NaN because the whole string is not numeric. parseFloat("42px") is 42 because it reads a decimal number from the start and stops at the first non-number character.

String and Boolean conversion

String(value) is for display. It turns a value into text you can put in a message. Template literals, like Total: 3, also convert pieces to strings while building display text.

What String(value) returns
ValueResultWhy
nullnullThe word null.
undefinedundefinedThe word undefined.
truetrueThe word true.
4242Digits as text.
-00Surprise: String(-0) is "0".
[1, 2]1,2Array items joined with commas.
[]An empty array becomes empty text.
{}[object Object]Plain object display text.
function demo() {}function(){}Functions stringify to source-like text.

Boolean(value) answers one question: is this value truthy or falsy? From the Booleans, null & undefined lesson, the falsy values are false, 0, -0, 0n, "", null, undefined, and NaN. Everything else is truthy.

Boolean(value): falsy values and tricky truthy values
ValueResultWhy
falsefalseAlready false.
0falseZero is falsy.
-0falseNegative zero is falsy too.
0nfalseBigInt zero is falsy.
""falseEmpty text is falsy.
nullfalseNo value is falsy.
undefinedfalseMissing value is falsy.
NaNfalseNot-a-number is falsy.
"0"trueNon-empty strings are truthy.
" "trueA space is still a character, so truthy.
[]trueObjects, including arrays, are truthy.
{}trueObjects are truthy.

That is why Boolean(" ") is true: a space is still a character. It is also why Boolean("false") and Boolean("0") are true. Boolean conversion does not read English words inside strings.

Operators convert too

STEP THROUGH

Operators often ask for a type. Multiplication wants numbers. Division wants numbers. Greater-than usually wants comparable numbers when the values are numeric-looking. The tricky operator is +, because it has two jobs: add numbers or join strings.

In this replay, lines 1 and 2 stay the same. Switch only the operator on line 3 and predict what line 4 prints.

Switch the operator
Step 0 of 4Ready
Your turn: follow the blue line

Switch the operator and predict line 4. Only + prefers strings; the others convert to numbers.

Running in
  1. script
Next: line 1
Click the blue line to take the next stepPop out in the code editor (opens in a new tab)JavaScript
const right = 2;const result = left + right;console.log(result);
CallStoreChangeResultRun = next line. Ran = already executed.
Recent returnsNothing yet. Start with the blue line.
Change line 3: which operator sits between the values?

Changing the operator starts a fresh replay. Predict the printed value before stepping.

A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

Now compare a wider set of implicit conversions recorded from real code. These are the same kinds of examples you will meet again in the later Type coercion and Equality & sameness lessons; for now, focus on the practical operator behavior.

Implicit conversion in real expressions
Step 0 of 7Ready
Your turn: follow the blue line

Step through real implicit conversions. The source uses console.log so the values are easy to compare.

Running in
  1. script
Next: line 1
Click the blue line to take the next stepPop out in the code editor (opens in a new tab)JavaScript
console.log("5" + 2);console.log("5" - 2);console.log(true + 1);console.log(null + 1);console.log(undefined + 1);console.log("3" > 2);
CallStoreChangeResultRun = next line. Ran = already executed.
Recent returnsNothing yet. Start with the blue line.
A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

Common surprises, with the explicit fix

FUN FACT

Some conversion examples are famous because they look like jokes. They are real, but you do not need to write code like this. Use them as a stress test for your mental model, then use explicit conversion in real programs.

Common surprises gallery
Step 0 of 9Ready
Your turn: follow the blue line

A small gallery of famous conversion surprises. Predict first; every frame is recorded from real JavaScript behavior.

Running in
  1. script
Next: line 1
Click the blue line to take the next stepPop out in the code editor (opens in a new tab)JavaScript
console.log([] + {});console.log("b" + "a" + +"a" + "a");console.log("10" / "2");console.log("1" + 1 - 1);console.log(0.1 * "3");console.log(Number(" \n "));console.log(Boolean(" "));console.log(String(-0));
CallStoreChangeResultRun = next line. Ran = already executed.
Recent returnsNothing yet. Start with the blue line.
A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.
  • [] + [] becomes empty text because both arrays become empty strings before + joins them.
  • [] + becomes "[object Object]" because an empty array becomes "" and a plain object becomes that display string.
  • "b" + "a" + +"a" + "a" becomes "baNaNa": unary plus tries to make "a" a number, gets NaN, then string joining continues.
The deeper rules come later

Objects have their own conversion path involving primitive values. That belongs in the later Object to primitive conversion lesson. Loose equality has its own algorithm too, covered in Equality & sameness. This lesson keeps the everyday rule: convert on purpose when correctness matters.

Where you will use this

The most common place is user input. Text boxes, prompts, URL pieces, and saved settings often arrive as strings. Convert them at the edge of your program, validate the result, and let the rest of your code use the correct type.

Fixing the prompt addition bugPop out in the code editor (opens in a new tab)JavaScript
const ageText = prompt("How old are you?");const age = Number(ageText); if (Number.isNaN(age)) {  console.log("Please type a number.");} else {  console.log(age + 1);}

Without the conversion, a user typing 25 gives you the string "25". "25" + 1 joins text into "251". With Number(ageText), the program can do real arithmetic and print 26. The Number.isNaN branch handles input like "twenty".

Practical rules of thumb
  • Convert user input explicitly at the edge of the program.
  • Use Number(value) and check Number.isNaN before math.
  • Prefer template literals or String(value) for display text.
  • Avoid clever expressions that depend on implicit conversion.
  • Prefer ===; comparison operators are up next.

Common misconceptions

“The plus sign always adds.”

+ adds numbers, but it also joins strings. If a string is involved, expect text joining unless you converted first.

“Blank numeric input becomes NaN.”

Number("") is 0. If blank should be an error, check the trimmed string before converting.

“Boolean() understands words.”

It does not. Boolean("false") is true because the string is non-empty.

“String(value) is a nice formatter for every object.”

String() is "[object Object]". For structured data, format the exact fields you want or use a later tool such as JSON deliberately.

“NaN can be checked with ===.”

NaN === NaN is false. Use Number.isNaN(value) for the converted number.

Practice: convert on purpose

5 EXERCISES
Exercise 1 · Warm-upPredict three conversions

Predict the three printed values. Write them separated by commas.

Starter codePop out in the code editor (opens in a new tab)JavaScript
console.log(Number(" 42 "));
console.log(Boolean(" "));
console.log(String(-0));

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · PracticeFix the prompt addition bug

    First, predict the bug. Then compare it with the solution code: the fix is Number() plus a Number.isNaN() check.

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    const ageText = "25";
    console.log(ageText + 1);

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeConvert a number for display

      What message does this display program print?

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      const items = 3;
      const message = "Items: " + String(items);
      console.log(message);

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeSpot the implicit conversion

        Which snippet converts a value without naming String, Number, or Boolean?

        • Number(input)
        • String(42)
        • score * "2"

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeExplain baNaNa

          Predict the exact output of the famous banana expression.

          Starter codePop out in the code editor (opens in a new tab)JavaScript
          console.log("b" + "a" + +"a" + "a");

          Answer, then press Check. Spacing and letter case don’t matter.

            Quiz: check your understanding

            8 QUESTIONS

            For every code question, name the type of each value first, then ask what type the function or operator wants.

            Lesson quiz · 8 questionsScore: first tries count
            1. Question 1 of 8Which line converts a value to a number on purpose?

              Choose an answer to see the explanation.

            2. Question 2 of 8What does Number("42px") print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              console.log(Number("42px"));

              Choose an answer to see the explanation.

            3. Question 3 of 8What does Number(" \n ") print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              console.log(Number(" \n "));

              Choose an answer to see the explanation.

            4. Question 4 of 8What does "5" + 2 print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              console.log("5" + 2);

              Choose an answer to see the explanation.

            5. Question 5 of 8What does "1" + 1 - 1 print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              console.log("1" + 1 - 1);

              Choose an answer to see the explanation.

            6. Question 6 of 8Which value is falsy?

              Choose an answer to see the explanation.

            7. Question 7 of 8What is the safest first step after reading numeric user input?

              Choose an answer to see the explanation.

            8. Question 8 of 8What does the baNaNa expression print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              console.log("b" + "a" + +"a" + "a");

              Choose an answer to see the explanation.

            Key takeaways

            • String(), Number(), and Boolean() convert values explicitly.
            • Number() needs the whole value to be numeric; failed conversion gives NaN.
            • Boolean() follows the falsy list; non-empty strings and all objects are truthy.
            • + is special because it may join strings; -, *, and / convert toward numbers.
            • Convert user input at the edge, check it, then keep the correct type through the rest of your program.

            Remember the one-liner.
            Type conversion is changing a value’s type on purpose; coercion is JavaScript changing it for you.

            Up next: Operators, where you will use arithmetic, comparisons, === versus ==, and logical operators with fewer surprises.

            CompleteFrontend Clear concepts. Working examples.