Ad space (banner)
🟨JavaScript Lessons
Lesson 32 / 69

The Basics of Type Conversion (Casting)

In this lesson you'll learn the basics of type conversion (casting) in JavaScript so you can correctly convert between strings and numbers. This is for people searching "JavaScript how to convert types" or "JavaScript string to number conversion."

Type conversion (casting) — converting a string to a number, or a number to a string — is a basic programming operation. You use Number(), String(), parseInt(), and similar functions. Values from a form always arrive as strings, so you must always convert them to numbers before using them in a calculation. Performing arithmetic without being mindful of types is a common source of unexpected bugs.

The sample code converts the string "123" to a number with Number() and uses it in a calculation, and converts the number 45 to a string with String() to join it with the character "yen." parseInt() is a function that pulls out only the part of a string that can be read as a number from the front, so it can extract just the number from a string with a unit attached, like "123px".

A common beginner stumbling block is using the + operator while still thinking of a value as a number even though it's still a string, which ends up concatenating strings instead of adding. "5" + 3 doesn't produce 8 — it produces the string "53". Confusingly, "5" - 3 is automatically converted to numbers and produces 2, so the way different operators behave can be a source of confusion.

In real development, input values from forms and URL parameters are always treated as strings, so you must always insert an appropriate type conversion before doing calculations involving money or dates. Code that's mindful of types is fundamental to building a stable app with fewer bugs.

JavaScript
OUTPUT

💡 Anything passed to console.log() appears in the output below.

Ad space (banner)
Ad space (in-article)