In this chapter, we will learn about JavaScript type conversion.
We will cover:
- What is Type Conversion?
- Implicit Type Conversion
- Explicit Type Conversion
What is Type Conversion?
Type conversion is the process of converting a value from one data type to another. In JavaScript, this can happen automatically (implicit conversion) or manually (explicit conversion).
Implicit Type Conversion
Implicit type conversion, also known as type coercion, happens automatically when JavaScript tries to make sense of an operation involving different types.
Examples of Implicit Conversion
-
String to Number (Addition)
let result = '5' + 2; console.log(result); // Output: "52" (string)
-
String to Number (Subtraction)
let result = '5' - 2; console.log(result); // Output: 3 (number)
-
Boolean to Number
let result = true + 1; console.log(result); // Output: 2 (true is converted to 1) result = false + 1; console.log(result); // Output: 1 (false is converted to 0)
-
Number to String
let result = 'The answer is ' + 42; console.log(result); // Output: "The answer is 42" (number 42 is converted to string)
Explicit Type Conversion
Explicit type conversion, also known as type casting, is done manually by using built-in functions.
Examples of Explicit Conversion
-
String to Number
let str = "123"; let num = Number(str); console.log(num); // Output: 123 (number) let invalidStr = "abc"; let invalidNum = Number(invalidStr); console.log(invalidNum); // Output: NaN (Not-a-Number)
-
Number to String
let num = 123; let str = String(num); console.log(str); // Output: "123" (string)
-
Boolean to Number
let bool = true; let num = Number(bool); console.log(num); // Output: 1 (number) bool = false; num = Number(bool); console.log(num); // Output: 0 (number)
-
Number to Boolean
let num = 1; let bool = Boolean(num); console.log(bool); // Output: true (boolean) num = 0; bool = Boolean(num); console.log(bool); // Output: false (boolean)
-
String to Boolean
let str = "Hello"; let bool = Boolean(str); console.log(bool); // Output: true (non-empty string is true) str = ""; bool = Boolean(str); console.log(bool); // Output: false (empty string is false)
Using parseInt() and parseFloat()
These functions are used to convert strings to numbers, but they work slightly differently from Number()
.
Examples of parseInt()
and parseFloat()
-
Using
parseInt()
let str = "123"; let num = parseInt(str); console.log(num); // Output: 123 (number) str = "123.45"; num = parseInt(str); console.log(num); // Output: 123 (number, decimal part is ignored)
-
Using
parseFloat()
let str = "123.45"; let num = parseFloat(str); console.log(num); // Output: 123.45 (number) str = "123"; num = parseFloat(str); console.log(num); // Output: 123 (number)
Conclusion
In this chapter, you learned about type conversion in JavaScript, including both implicit and explicit conversions. Understanding type conversion is essential for avoiding unexpected results in your code.