AI Hints
JavaScript · Lesson 17 of 138

Converting Types

Number(), String().

⏱ 2 min read▶ Video at 19:41🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Values that come from users, files, and web pages often arrive as strings, even when they look like numbers. Before you do maths with them, convert them yourself.

Converting Types
From the video: Converting Types
  • User input is text
  • Even numbers
  • Convert before maths

Number, String, parseInt

Number turns a string into a number, so the maths works properly. If the text isn't a number, you get NAN, which means not a number. String turns a value into text. And parse int reads a whole number from the start of a string. Run it.

app.jsjavascript
const typed = "42";
console.log(typed + 8);
console.log(Number(typed) + 8);

console.log(Number("hello"));
console.log(String(99) + "!");
console.log(parseInt("100px"));
Output
428
50
NaN
99!
100

Checking for NaN

NAN is strange. It's a number type, but it's not equal to anything, not even itself. So to check for it, use number dot is NAN. When reading user input, always convert, then check, before you trust it.

keyvalue
Number('42')42
Number('hi')NaN
parseInt('100px')100
CheckNumber.isNaN(x)

Summary

Convert strings to numbers with Number or parse int, and numbers to strings with String. Watch out for NAN. Next, a quiz on the basics.

Key takeaways
  • Number()
  • String()
  • Number.isNaN
Next up: Basics Quiz — test yourself