Sometimes you have a value of one type, but you need it to be another type. The classic example is prompt, which always gives you back a string, even if the user types a number:
const age = prompt("How old are you?"); // user types 25
console.log(age + 1);
Output
251
Uh oh. The user typed 25, but prompt gave us the string "25". When we add 1, JavaScript glues them together like text: "25" + 1 = "251". Congratulations, you're 251 years old. Professor Semicolon says welcome to the club.
The fix is to convert the string into a number first. Here are the tools for converting types:
Converting to a number
console.log(Number("25"));
console.log(Number("3.5"));
console.log(Number("hello"));
console.log(Number(""));
console.log(parseInt("42px"));
console.log(parseFloat("3.75 metres"));
It prints
25 3.5 NaN 0 42 3.75
Number(value)converts the whole thing. If it can't make sense of it, you getNaN. (Watch out: an empty string becomes0.)parseInt(value)reads a whole number from the start of a string and stops at the first character that isn't a digit. Handy for things like"42px".parseFloat(value)does the same thing, but allows a decimal point.
So the fixed age program looks like this:
const age = Number(prompt("How old are you?")); // user types 25
console.log(age + 1);
Output
26
Much better. Professor Semicolon is disappointed that you're no longer in his age group, but he'll get over it.
Converting to a string
const score = 99;
console.log(String(score));
console.log(score.toString());
console.log(typeof String(score));
It prints
99 99 string
You can also convert to a boolean with Boolean(value), but that opens up a fascinating can of worms called "truthy and falsy," which we'll save for Grade 4.