completefrontend
Open lab My progress
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
    Pick the right functionUse String(), Number(), and Boolean() on purpose, for the type you need next.
  • 02
    Spot hidden conversionsPredict when signs like + and - convert values for you.
  • 03
    Handle 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.
  • 25 is a number.
  • true is 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.

Three conversions you ask for by namePop out in the code editor (opens in a new tab)JavaScript
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 number 7.
  • Line 3: String(7) turns the number into the text "7".
  • Line 4: Boolean(7) turns the number into true.

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.

The main idea

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 plain true or false.

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()

INTERACTIVE

JavaScript 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 back true or false.
The text "7" goes to three functions. Number() gives the number 7. String() gives the text "7". Boolean() gives true."7"Number()String()Boolean()7"7"truea numbera stringa boolean
The same value, "7", given to three functions. Each function always gives back its own type: Number() a number, String() a string, and Boolean() a boolean.
Real-life analogyThree translators at a help desk

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.
  • +value is a plus sign in front of one value. It is called unary plus, and it does the same as Number(value).
Converter playground
Six ways to convert one valuePop 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));
What each line gives"42px"
Number(value)NaN

Turns the whole value into a number.

parseFloat(value)42

Reads a number from the start of the text.

+valueNaN

Unary plus. It does the same as Number(value).

String(value)"42px"

Turns the value into text.

Boolean(value)true

Gives true for truthy values and false for falsy ones.

Number.isNaN(Number(value))true

Gives true when the Number() conversion failed.

Try it yourself

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.

The playground runs the same six conversions on your text. It never runs your text as JavaScript code.

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

SORT

There 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" - 2 subtracts. Subtraction needs numbers, so JavaScript turns "5" into 5 first.
  • if (items.length) needs a yes or no. So JavaScript turns the number into a boolean first.
Real-life analogyChanging money on a trip

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

Sort each piece of code. Explicit: the code asks for the conversion. Implicit: JavaScript converts while it does something else.

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

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."

What Number(value) gives for common values
When you convertYou getWhy
""0Empty text becomes 0.
" 42 "42The spaces at both ends are removed first.
"42px"NaNThe px part is not a number, so the whole conversion fails.
"0x1A"260x starts a base-16 (hexadecimal) number. 1A in base 16 is 26.
"1e3"1000e3 means "times 10 three times", so this is 1 × 1000.
null0null becomes 0.
undefinedNaNundefined becomes NaN.
true1true becomes 1.
false0false becomes 0.
[]0An empty array first becomes empty text, and empty text becomes 0.
[5]5An array with one item first becomes the text "5".
[1, 2]NaNThis array first becomes the text "1,2", which is not a number.
{}NaNA 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() and parseFloat()

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.

The text "42px" goes to two functions. Number() needs all of it to be a number, so it gives NaN. parseFloat() reads 42 from the start and stops at px."42px"Number()parseFloat()NaN42needs all of itstops at px
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".

Number() reads the whole text; parseInt() reads the startPop out in the code editor (opens in a new tab)JavaScript
console.log(Number("12px"));
console.log(parseInt("12px", 10));
console.log(Number(" 12 "));
console.log(Number(""));
  • Line 1 prints NaN. Number() can't use the px at the end.
  • Line 2 prints 12. parseInt() reads 12 and stops at px.
  • Line 3 prints 12. The spaces around 12 are removed first.
  • Line 4 prints 0. Empty text becomes 0.

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."

What String(value) gives for common values
When you convertYou getWhy
nullnullYou get the word null.
undefinedundefinedYou get the word undefined.
truetrueYou get the word true.
4242You get the digits as text.
-00The minus sign is dropped, so you get "0".
[1, 2]1,2The 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.
Two ways to turn a number into textPop out in the code editor (opens in a new tab)JavaScript
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."

What Boolean(value) gives: all falsy values, then some tricky truthy ones
When you convertYou getWhy
falsefalseIt is already false.
0falseZero is falsy.
-0falseMinus zero is falsy too.
0nfalseThe BigInt zero is falsy.
""falseEmpty text is falsy.
nullfalsenull means "no value". It is falsy.
undefinedfalseundefined means "not set yet". It is falsy.
NaNfalseNaN means "not a number". It is falsy.
"0"trueThis text has one character, so it is not empty. It is truthy.
" "trueA space is still a character, so this text is truthy.
[]trueEvery array is an object, and every object is truthy, even an empty one.
{}trueEvery 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.

Four texts given to Boolean(). The empty text "" gives false. A space " ", "0", and "false" all give true, because none of them is empty.""" ""0""false"falsetruetruetrueemptynot emptynot emptynot empty
For text, 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 THROUGH

An 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.
The plus sign has two jobsPop out in the code editor (opens in a new tab)JavaScript
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.

Left: "5" + 1 joins the two into the text "51". Right: "5" - 1 turns "5" into a number and gives 4."5"+1"51"joins text"5"-14does math
The same two values with a different sign. With + 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.

Change the operator on line 3
Step 0 of 4Ready
Your turn: follow the blue line

Pick another operator and guess what line 4 prints. Only + joins text; the others turn the string into a number.

Running in
  1. script
Next: line 1
const right = 2;const result = left + right;console.log(result);
CallStoreChangeResultBlue line: runs next. Ran: already executed.
Recent returnsNothing yet. Start with the blue line.
Line 3: which operator goes between the two values?

A new operator starts the replay again. Guess what line 4 prints before you step.

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.

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.

Seven conversions JavaScript does for you
Step 0 of 7Ready
Your turn: follow the blue line

Each line converts a value without asking. Step through and compare what each operator needs.

Running in
  1. script
Next: line 1
console.log("5" + 2);console.log("5" - 2);console.log(true + 1);console.log(null + 1);console.log(undefined + 1);console.log("3" > 2);
CallStoreChangeResultBlue line: runs next. 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.

Strange results, and how to avoid them

FUN FACT

Some 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.

Famous strange results
Step 0 of 9Ready
Your turn: follow the blue line

Nine famous strange results, each run in real JavaScript. Guess each one before you step.

Running in
  1. script
Next: line 1
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));
CallStoreChangeResultBlue line: runs next. 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.

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 gets NaN. The other + signs join it all into text.
The full rules come later

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:

  1. Convert the value as soon as it comes into your program.
  2. Check that the conversion worked.
  3. Use the converted value everywhere after that.
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);}

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 age is a real number. It does real math and prints 26.
Add up a form totalPop out in the code editor (opens in a new tab)JavaScript
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.

Habits to keep
  • Convert user input on purpose, as soon as it comes in.
  • Use Number(value), then check Number.isNaN before 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 EXERCISES
Exercise 1 · Warm-upPredict three conversions

Guess the three values this program prints. Write them with commas between them.

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, guess what the buggy code prints. 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 · PracticeTurn a number into text for a message

      What message does this 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 piece of code converts a value without calling 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

          Guess the exact output of this famous line of code.

          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 each code question, first name the type of each value. Then ask which type the function or operator needs.

            Lesson quiz · 8 questionsScore: first tries count
            1. Question 1 of 8Which line turns a value into 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 8The user typed a number into a box. What should your code do first?

              Choose an answer to see the explanation.

            8. Question 8 of 8What does the baNaNa line 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 a value on purpose. This is explicit conversion.
            • Number() needs the whole value to be a number. If it isn't, you get NaN.
            • Boolean() gives false only for the eight falsy values. Text that isn't empty, and every object, gives true.
            • + 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.

            CompleteFrontend Clear concepts. Working examples.