Type conversion
Turn JavaScript values into strings, numbers, and booleans on purpose, and recognize the implicit conversions behind common surprises.
- 01Pick the right functionUse String(), Number(), and Boolean() on purpose, for the type you need next.
- 02Spot hidden conversionsPredict when signs like + and - convert values for you.
- 03Handle user input safelyTurn typed text into a number as soon as it comes in, then check for NaN.
Why conversion matters
Every value in JavaScript has a type:
"25"is a string, which means text. The quotes show that.25is a number.trueis a boolean, which means a yes-or-no value.
"25" and 25 look almost the same on the screen. But they act differently when you do math, build a message, or make a decision.
Type conversion means turning a value of one type into a value of another type. Sometimes you ask for it yourself. Other times JavaScript does it without telling you, because a sign like + or - needs a certain type. This lesson shows both, and how to tell them apart.
const scoreText = "7";
console.log(Number(scoreText));
console.log(String(7));
console.log(Boolean(7));Line 1 stores the text "7". Lines 2, 3, and 4 each call a function that names the type it wants:
- Line 2:
Number(scoreText)turns the text into the number7. - Line 3:
String(7)turns the number into the text"7". - Line 4:
Boolean(7)turns the number intotrue.
The console shows 7, 7, and true. It doesn't show quotes around text, so the first two lines look the same even though one is a number and one is a string.
Convert a value when the next line needs a different type:
- Use
Number()before math. - Use
String()before showing text to the user. - Use
Boolean()when you need a plaintrueorfalse.
Earlier lessons showed a puzzle. "5" + 3 gives "53", but "5" - 3 gives 2. The Interaction lesson also showed that prompt() always gives back a string, so "25" + 1 gives "251". By the end of this lesson, you will be able to predict results like these.
String(), Number(), and Boolean()
INTERACTIVEJavaScript has three built-in functions for conversion. Each one has the name of the type it gives back:
Number(value)gives back a number.String(value)gives back a string.Boolean(value)gives backtrueorfalse.
"7", given to three functions. Each function always gives back its own type: Number() a number, String() a string, and Boolean() a boolean.At an airport help desk there are three translators. Each one speaks one language. You pick the translator who speaks the language you need next. In the same way, you pick the conversion function for the type your next line needs.
- In real life: The translator who speaks numbers
- In JavaScript:
Number(value): use it before math - In real life: The translator who speaks text
- In JavaScript:
String(value): use it before showing text - In real life: The translator who only says yes or no
- In JavaScript:
Boolean(value): use it before a decision
Try the playground below. Type any text, or click one of the ready-made values. The code stays the same. Only the value on line 1 changes. The playground also shows two more tools:
parseFloat(value)reads a number from the start of a string.+valueis a plus sign in front of one value. It is called unary plus, and it does the same asNumber(value).
const value = "42px";Number(value);parseFloat(value);+value;String(value);Boolean(value);Number.isNaN(Number(value));Turns the whole value into a number.
Reads a number from the start of the text.
Unary plus. It does the same as Number(value).
Turns the value into text.
Gives true for truthy values and false for falsy ones.
Gives true when the Number() conversion failed.
Click a ready-made value or type your own. Your text is only converted, never run as code.
Number() needs all of the text to be a number. parseFloat() reads from the start and stops where the number ends.
Look at what happens with "42px". Number() needs the whole value to be a number. The px part is not a number, so it gives NaN, which means "Not a Number". parseFloat() is less strict. It reads 42 from the start and stops at px. Unary plus gives the same answer as Number().
Explicit and implicit conversion
SORTThere are two ways a value can change type.
Explicit conversion means you ask for it in the code. You can point at the line where it happens. Number(input) says "make a number here". String(total) says "make text here".
Implicit conversion means JavaScript converts the value for you while it does another job. Nothing in the code asks for it:
"5" - 2subtracts. Subtraction needs numbers, so JavaScript turns"5"into5first.if (items.length)needs a yes or no. So JavaScript turns the number into a boolean first.
On a trip, you can go to an exchange booth and ask for euros. You see the rate, and you know what you get. Or you can pay in a shop with dollars. The shop changes your money at its own rate, and you find out the price later.
- In real life: You go to the exchange booth and ask for euros
- In JavaScript: Explicit:
Number(value)asks for a number - In real life: A shop takes your dollars and changes them for you
- In JavaScript: Implicit: a sign like
-converts while it does its own job - In real life: At the booth you can see the rate
- In JavaScript: You can see a named conversion in the code
Number(input)"Total: " + priceif (items.length)String(42)score * "2"!!value
Sort each piece of code. Explicit: the code asks for the conversion. Implicit: JavaScript converts while it does something else.
Implicit conversion is not always wrong. Most code uses it in conditions, like if (items.length). The habit to build is this: convert explicitly as soon as a value comes into your program, especially text the user typed.
What Number() gives back
Use Number(value) first when you need a number. It always gives back one of two things:
- a number, when the value can be read as a number;
NaN, a special number value that means "Not a Number", when it can't.
After you convert, check the result with Number.isNaN(result). It gives true when the conversion failed.
The table below shows common values. Read each row as: "Number() of this value gives this result, for this reason."
| When you convert | You get | Why |
|---|---|---|
"" | 0 | Empty text becomes 0. |
" 42 " | 42 | The spaces at both ends are removed first. |
"42px" | NaN | The px part is not a number, so the whole conversion fails. |
"0x1A" | 26 | 0x starts a base-16 (hexadecimal) number. 1A in base 16 is 26. |
"1e3" | 1000 | e3 means "times 10 three times", so this is 1 × 1000. |
null | 0 | null becomes 0. |
undefined | NaN | undefined becomes NaN. |
true | 1 | true becomes 1. |
false | 0 | false becomes 0. |
[] | 0 | An empty array first becomes empty text, and empty text becomes 0. |
[5] | 5 | An array with one item first becomes the text "5". |
[1, 2] | NaN | This array first becomes the text "1,2", which is not a number. |
{} | NaN | A plain object first becomes the text "[object Object]", which is not a number. |
The most useful surprise is blank text. Number("") gives 0. So does Number(" \n "), which holds only spaces and a line break. JavaScript first removes spaces and line breaks from both ends of the text. If nothing is left, the answer is 0.
If blank input should count as a mistake, check for it before you convert. value.trim() gives the text without spaces at the ends, so value.trim() === "" is true for blank text.
Number("42px") is NaN, because the whole text is not a number. parseFloat("42px") is 42, because it reads a number from the start and stops at the first character that can't be part of a number.
Number() looks at the whole text. The px part is not a number, so the answer is NaN. parseFloat() reads digits from the start and stops at px, so the answer is 42.The next example also uses parseInt(text, 10). It works like parseFloat(), but it only reads whole numbers. The 10 means "read it as a normal base-10 number".
console.log(Number("12px"));
console.log(parseInt("12px", 10));
console.log(Number(" 12 "));
console.log(Number(""));- Line 1 prints
NaN.Number()can't use thepxat the end. - Line 2 prints
12.parseInt()reads12and stops atpx. - Line 3 prints
12. The spaces around12are removed first. - Line 4 prints
0. Empty text becomes0.
What String() and Boolean() give back
String(value) turns a value into text, so you can show it in a message. A template literal does this too. It is text between backticks, like `Items: ${items}`. Each ${...} part is turned into text and placed inside.
Read each row of the next table as: "String() of this value gives this text."
| When you convert | You get | Why |
|---|---|---|
null | null | You get the word null. |
undefined | undefined | You get the word undefined. |
true | true | You get the word true. |
42 | 42 | You get the digits as text. |
-0 | 0 | The minus sign is dropped, so you get "0". |
[1, 2] | 1,2 | The items are joined with commas. |
[] | An empty array becomes empty text. | |
{} | [object Object] | Every plain object becomes this same text. |
function demo() {} | function(){} | A function becomes the text of its own code. |
const items = 3;
console.log(`Items: ${items}`);
console.log(String(items));Line 2 uses a template literal and prints Items: 3. Line 3 uses String(items) and prints 3. Both are good ways to build text for a page.
Boolean(value) answers one question: is this value truthy or falsy? A truthy value counts as true in an if. A falsy value counts as false. You met this list in the Booleans, null & undefined lesson. These are all the falsy values: false, 0, -0, 0n, "", null, undefined, and NaN. Every other value is truthy.
The next table shows each falsy value, then four truthy values that often trick people. Read each row as: "Boolean() of this value gives this result."
| When you convert | You get | Why |
|---|---|---|
false | false | It is already false. |
0 | false | Zero is falsy. |
-0 | false | Minus zero is falsy too. |
0n | false | The BigInt zero is falsy. |
"" | false | Empty text is falsy. |
null | false | null means "no value". It is falsy. |
undefined | false | undefined means "not set yet". It is falsy. |
NaN | false | NaN means "not a number". It is falsy. |
"0" | true | This text has one character, so it is not empty. It is truthy. |
" " | true | A space is still a character, so this text is truthy. |
[] | true | Every array is an object, and every object is truthy, even an empty one. |
{} | true | Every object is truthy, even an empty one. |
So Boolean(" ") is true, because a space is still a character. Boolean("false") and Boolean("0") are true too. Boolean() doesn't read the words inside a string. It only checks if the string is empty.
Boolean() only asks one question: is the text empty? Only "" is empty. A space, "0", and even "false" each have characters, so each gives true.Operators convert too
STEP THROUGHAn operator is a sign that does a job with values, like +, -, *, or >. Many operators need a certain type, and convert values to get it:
-,*(multiply), and/(divide) only do math, so they turn strings into numbers.>(greater than) compares two values. When one side is a number, it turns the other side into a number too.+is the tricky one. It has two jobs: it adds numbers, and it joins strings into one longer string.
console.log("5" + 1);
console.log("5" - 1);Line 1 has a string on one side of +, so + joins text. The 1 becomes "1", and the console prints 51. Line 2 uses -, which can only subtract. So "5" becomes the number 5, and the console prints 4.
+ and a string on one side, JavaScript joins text. - can only do math, so JavaScript turns "5" into the number 5 first.Now try it step by step. In this replay, lines 1 and 2 stay the same. Pick a different operator for line 3, and guess what line 4 prints before you step through.
Pick another operator and guess what line 4 prints. Only + joins text; the others turn the string into a number.
script
const right = 2;const result = left + right;console.log(result);The next replay has seven more implicit conversions, each run in real JavaScript. Later lessons, Type coercion and Equality & sameness, explain the full rules behind them. For now, watch which type each operator needs.
Each line converts a value without asking. Step through and compare what each operator needs.
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);Strange results, and how to avoid them
FUN FACTSome conversion results are famous because they look like jokes. They are real JavaScript. You never need to write code like this. But if you can explain each one, you understand the rules. Each step in the replay also says how to write that line clearly.
Nine famous strange results, each run in real JavaScript. Guess each one before you step.
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));Here is why the first three lines print what they print:
[] + []prints empty text.+turns each empty array into empty text, then joins two empty texts.[] + {}prints"[object Object]". The empty array becomes"", and a plain object becomes the text"[object Object]"."b" + "a" + +"a" + "a"prints"baNaNa". The+right in front of the second"a"is unary plus. It tries to turn"a"into a number and getsNaN. The other+signs join it all into text.
Objects follow their own steps when they become text or numbers. The Object to primitive conversion lesson covers those steps. The == sign also has its own rules, covered in Equality & sameness. For this lesson, one rule is enough: when the result matters, convert on purpose.
Where you will use this
You will use conversion most with user input. Text boxes, prompt(), parts of a web address, and saved settings almost always give you strings, even when they look like numbers. The safe habit has three steps:
- Convert the value as soon as it comes into your program.
- Check that the conversion worked.
- Use the converted value everywhere after that.
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);}Line 1 asks the user their age. If they type 25, ageText holds the string "25". Without line 2, ageText + 1 would join text and give "251".
- Line 2 turns the text into a number with
Number(ageText). - Line 4 checks if that failed. For text like
"twenty", line 5 asks the user to type a number. - Line 7 runs only when
ageis a real number. It does real math and prints26.
const priceText = "12";
const quantityText = "3";
const price = Number(priceText);
const quantity = Number(quantityText);
const total = price * quantity;
console.log(`Total: ${total}`);The boxes in a web form give you strings, even when the user typed digits. Lines 1 and 2 stand in for those form values. Lines 3 and 4 turn the price and the quantity into numbers. Then line 5 can multiply them, and line 6 prints Total: 36.
- Convert user input on purpose, as soon as it comes in.
- Use
Number(value), then checkNumber.isNaNbefore math. - Use template literals or
String(value)to build text. - Avoid clever code that only works because of implicit conversion.
- Compare with
===. The next lessons on operators explain why.
Common misconceptions
"The plus sign always adds."
+ adds numbers, but it also joins strings. If either side is a string, expect joined text, unless you converted the string to a number first.
"Blank number input becomes NaN."
Number("") is 0, not NaN. If blank input should be a mistake, check value.trim() === "" before you convert.
"Boolean() understands words."
It doesn't. Boolean("false") is true, because the string is not empty.
"String(value) shows any object nicely."
String({}) is "[object Object]" for every plain object. To show an object, build the text from the exact properties you want. A later lesson shows another tool for this, called JSON.
"You can check for NaN with ===."
NaN === NaN is false. NaN is never equal to anything, not even itself. Use Number.isNaN(value) instead.
Practice: convert on purpose
5 EXERCISESGuess the three values this program prints. Write them with commas between them.
console.log(Number(" 42 "));
console.log(Boolean(" "));
console.log(String(-0));The program prints 42, then true, then 0. The second line is true because " " holds one character, a space, so it is not empty. The third line prints 0 because String(-0) gives "0".
First, guess what the buggy code prints. 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. To fix it, convert first with Number(ageText). Then check Number.isNaN(age), and only after that add 1. For "25", the fixed version prints 26.
What message does this 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) shows the conversion in the code. The console prints Items: 3. A template literal like Items: ${items} would also work well.
Which piece of code converts a value without calling String, Number, or Boolean?
Number(input)String(42)score * "2"
score * "2" is the implicit conversion. * can only multiply numbers, so JavaScript turns the string "2" into the number 2 without being asked.
Guess the exact output of this famous line of code.
console.log("b" + "a" + +"a" + "a");It prints baNaNa. "b" + "a" makes "ba". Unary +"a" becomes NaN. Then the other + signs join all the pieces as text.
Quiz: check your understanding
8 QUESTIONSFor each code question, first name the type of each value. Then ask which type the function or operator needs.
Question 1 of 8Which line turns a value into 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 8The user typed a number into a box. What should your code do first?
Choose an answer to see the explanation.
Question 8 of 8What does the
baNaNaline print?Read the code, then predictconsole.log("b" + "a" + +"a" + "a");Choose an answer to see the explanation.
Key takeaways
String(),Number(), andBoolean()convert a value on purpose. This is explicit conversion.Number()needs the whole value to be a number. If it isn't, you getNaN.Boolean()givesfalseonly for the eight falsy values. Text that isn't empty, and every object, givestrue.+joins text when one side is a string.-,*, and/turn strings into numbers.- Convert user input as soon as it comes in, check it, then keep using the converted value.
Remember the one-liner.
Type conversion turns a value into another type. Do it on purpose, so JavaScript doesn't do it for you by surprise.
Up next: Operators. You will use math signs, comparisons, === and ==, and logical operators, with fewer surprises.