Chapter 14
JavaScript Type Conversion
Type conversion means changing a value from one data type to another compatible type.
01 • Learn
What is JavaScript Type Conversion?
- User input from form fields is commonly received as a string.
- A numeric string may need to be converted to a number before performing calculations.
- String(), Number(), Boolean(), parseInt(), and parseFloat() are common conversion tools.
- Explicit conversion can make program behavior easier to understand and control.
02 • Syntax
Syntax
let value = '100'; let numberValue = Number(value); let textValue = String(100);
03 • Example
Example
Try understanding this code before running it.
let price = '500'; let quantity = '2'; let total = Number(price) * Number(quantity); console.log(total);
04 • Remember
Important Points
- Number() is useful for converting values to numbers.
- String() converts a value to a string.
- parseInt() can parse an integer value from a string.
- parseFloat() can parse a decimal numeric value from a string.
- Invalid input should be handled because conversion can produce NaN.
05 • Avoid
Common Mistakes
- Treating form input strings as numbers without conversion.
- Confusing parseInt() with parseFloat().
- Ignoring NaN when input is invalid.
06 • Practical
Real-World Use
Type conversion is commonly required in registration forms, shopping carts, fee calculators, marks calculators, and API data processing.
07 • Practice
Practice Exercise
Practice: Type Conversion
Set price = '500' and quantity = '3'. Convert them to numbers and calculate the total price.
Ready to write code?
Open the JavaScript editor and run your code with live output.