Type conversion
Turn JavaScript values into strings, numbers, and booleans on purpose, and recognize the implicit conversions behind common surprises.
- 01Choose the right translatorUse String(), Number(), and Boolean() deliberately.
- 02Spot silent conversionsPredict when operators convert values for you.
- 03Handle 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.
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
INTERACTIVEThink 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.
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.
const value = "42px";Number(value);parseFloat(value);+value;String(value);Boolean(value);Number.isNaN(Number(value));Converts the whole value to a number.
Reads a decimal number from the start of a string.
A short form of Number(value).
Makes text for display.
Checks truthy or falsy.
Use this after Number to catch failed conversions.
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.
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
SORTExplicit 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.
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.
Number(input)"Total: " + priceif (items.length)String(42)score * "2"!!value
Sort each snippet by whether it asks for conversion directly or lets JavaScript convert while doing something else.
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).
| Value | Result | Why |
|---|---|---|
| "" | 0 | Empty string becomes 0. |
| " 42 " | 42 | Whitespace is trimmed first. |
| "42px" | NaN | The px makes the whole conversion fail. |
| "0x1A" | 26 | Hexadecimal notation is accepted. |
| "1e3" | 1000 | Scientific notation means 1 × 10³. |
| null | 0 | null becomes 0. |
| undefined | NaN | undefined becomes NaN. |
| true | 1 | true becomes 1. |
| false | 0 | false becomes 0. |
| [] | 0 | An empty array stringifies to empty text, then 0. |
| [5] | 5 | A one-item array stringifies to "5". |
| [1, 2] | NaN | "1,2" is not a valid number. |
| {} | NaN | Plain 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("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.
| Value | Result | Why |
|---|---|---|
| null | null | The word null. |
| undefined | undefined | The word undefined. |
| true | true | The word true. |
| 42 | 42 | Digits as text. |
| -0 | 0 | Surprise: String(-0) is "0". |
| [1, 2] | 1,2 | Array 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.
| Value | Result | Why |
|---|---|---|
| false | false | Already false. |
| 0 | false | Zero is falsy. |
| -0 | false | Negative zero is falsy too. |
| 0n | false | BigInt zero is falsy. |
| "" | false | Empty text is falsy. |
| null | false | No value is falsy. |
| undefined | false | Missing value is falsy. |
| NaN | false | Not-a-number is falsy. |
| "0" | true | Non-empty strings are truthy. |
| " " | true | A space is still a character, so truthy. |
| [] | true | Objects, including arrays, are truthy. |
| {} | true | Objects 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 THROUGHOperators 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 and predict line 4. Only + prefers strings; the others convert to numbers.
script
const right = 2;const result = left + right;console.log(result);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.
Step through real implicit conversions. The source uses console.log so the values are easy to compare.
script
console.log("5" + 2);console.log("5" - 2);console.log(true + 1);console.log(null + 1);console.log(undefined + 1);console.log("3" > 2);Common surprises, with the explicit fix
FUN FACTSome 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.
A small gallery of famous conversion surprises. Predict first; every frame is recorded from real JavaScript behavior.
script
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));[] + []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, getsNaN, then string joining continues.
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.
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".
- Convert user input explicitly at the edge of the program.
- Use
Number(value)and checkNumber.isNaNbefore 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 EXERCISESPredict the three printed values. Write them separated by commas.
console.log(Number(" 42 "));
console.log(Boolean(" "));
console.log(String(-0));The program prints 42, then true, then 0. The second result is true because " " contains a space character, and String(-0) displays as "0".
First, predict the bug. Then compare it with the solution code: the fix is Number() plus a Number.isNaN() check.
const ageText = "25";
console.log(ageText + 1);const ageText = "25";
const age = Number(ageText);
if (Number.isNaN(age)) {
console.log("Please type a number.");
} else {
console.log(age + 1);
}The buggy version prints 251. Convert first with Number(ageText), check Number.isNaN(age), and only then add 1. For "25", the fixed version prints 26.
What message does this display program print?
const items = 3;
const message = "Items: " + String(items);
console.log(message);const items = 3;
const message = "Items: " + String(items);
console.log(message);String(items) makes the conversion visible. The console prints Items: 3. A template literal like Items: ${items} would also be a good display choice.
Which snippet converts a value without naming String, Number, or Boolean?
Number(input)String(42)score * "2"
score * "2" is the implicit conversion. Multiplication wants numbers, so JavaScript converts the string "2" behind the scenes.
Predict the exact output of the famous banana expression.
console.log("b" + "a" + +"a" + "a");It prints baNaNa. "b" + "a" makes "ba". Unary +"a" becomes NaN. Then + "a" joins the text pieces.
Quiz: check your understanding
8 QUESTIONSFor every code question, name the type of each value first, then ask what type the function or operator wants.
Question 1 of 8Which line converts a value to a number on purpose?
Choose an answer to see the explanation.
Question 2 of 8What does
Number("42px")print?Read the code, then predictconsole.log(Number("42px"));Choose an answer to see the explanation.
Question 3 of 8What does
Number(" \n ")print?Read the code, then predictconsole.log(Number(" \n "));Choose an answer to see the explanation.
Question 4 of 8What does
"5" + 2print?Read the code, then predictconsole.log("5" + 2);Choose an answer to see the explanation.
Question 5 of 8What does
"1" + 1 - 1print?Read the code, then predictconsole.log("1" + 1 - 1);Choose an answer to see the explanation.
Question 6 of 8Which value is falsy?
Choose an answer to see the explanation.
Question 7 of 8What is the safest first step after reading numeric user input?
Choose an answer to see the explanation.
Question 8 of 8What does the
baNaNaexpression print?Read the code, then predictconsole.log("b" + "a" + +"a" + "a");Choose an answer to see the explanation.
Key takeaways
String(),Number(), andBoolean()convert values explicitly.Number()needs the whole value to be numeric; failed conversion givesNaN.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.