What is Type Casting?
Implicit Type Casting
let num = 10;
let str = “20”;
let result = num + str; // The result will be “1020”
In this example, the number `10` is implicitly converted to a string and concatenated with the string `”20″`.
Explicit Type Casting
Explicit type casting allows you to explicitly convert values from one data type to another using built-in functions or operators. It gives you more control over how your values are converted.
1. The Number() function: Converts a value into a number. 2.
The String() function: Converts a value into a string. 3. The Boolean() function: Converts a value into a boolean.
let num = “10”;
let str = 20;
let convertedNum = Number(num); // Now, convertedNum is a number
let convertedStr = String(str); // Now, convertedStr is a string
let bool = Boolean(str); // Now, bool is a boolean
In this example, we use the `Number()`, `String()`, and `Boolean()` functions to explicitly convert values into different data types.
Possible Data Type Conversions
1. Number to String: You can convert a number to a string using the `String()` function or by concatenating an empty string (`””`) with the number. String to Number: You can convert a string to a number using the `Number()` function or by using mathematical operations like addition or subtraction.
3. String to Boolean: An empty string (`””`) or the string `”0″` will be converted to `false`, while any other non-empty string will be converted to `true`. 4. Number to Boolean: The number `0` or `NaN` will be converted to `false`, while any other non-zero number will be converted to `true`.
It’s important to note that some conversions may result in unexpected behavior if the values cannot be accurately represented in the Target data type. For example, converting a large floating-point number into an integer may result in data loss.
List of Possible Data Type Conversions:
- Number to String
- String to Number
- String to Boolean
- Number to Boolean