Codiqo

Learn JavaScript · lesson 9 of 60 · about 7 minutes

Converting Types

Visitors type into boxes on Sam's page, and what they type is always text: turn it into a number before you add it up.

What you'll learn

  • Spot type mix-ups like '5' + 1
  • Convert with Number() and String()
  • Use parseInt() and parseFloat()

Everything typed is text

Sam's page is getting a box where visitors type how many days they've been coding. Whatever someone types in a box comes to your code as a string, even if it's only digits: "5", not 5.

That matters, because + joins as soon as one side is a string: "5" + 3 is "53". Other operators like - and * quietly turn text into numbers, which makes it even more confusing. typeof tells you which type you've got.

The same 5, as text

const daysText = "5";
console.log(daysText + 3);
console.log(daysText - 3);
console.log(typeof daysText, typeof 3);

Output

53
2
string number

Converting on purpose

Convert yourself, so there are no surprises:

| Function | Example | Result |
|---|---|---|
| Number() | Number("42") | 42 |
| String() | String(7) | "7" |
| parseInt() | parseInt("12px") | 12 |
| parseFloat() | parseFloat("3.5kg") | 3.5 |

Number ignores spaces around the digits, but anything else makes it give NaN, short for "Not a Number". parseInt and parseFloat read the digits at the start and stop at the first thing that isn't one.

Converting, then adding: the page gets it right

const daysText = "5";
const theirDays = Number(daysText);
document.querySelector("#days").textContent = `Together that's ${theirDays + 3} days of coding!`;

What each conversion gives

console.log(Number(" 7 "));
console.log(Number("5 days"));
console.log(parseInt("5 days"));
console.log(String(99) + "!");

Output

7
NaN
5
99!

Tip

When a sum comes out as two numbers stuck together, like 53, one of them is text. Find it and convert it.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.