In programming, type conversion is the process of converting data of one type to another, facilitating various operations and manipulations within code. JavaScript supports two types of type conversion: implicit and explicit.
In JavaScript, implicit conversion occurs automatically in certain situations, where the interpreter converts one data type to another as needed. Example 1: Implicit Conversion to String
let result;
result = '3' + 2;
console.log(result); // "32"
result = '3' + true;
console.log(result); // "3true"
Example 2: Implicit Conversion to Number
let result;
result = '4' - '2';
console.log(result); // 2
result = '4' * 2;
console.log(result); // 8
Example 3: Non-numeric String Results to NaN
let result;
result = 'hello' - 'world';
console.log(result); // NaN
Explicit conversion, also known as type casting, involves manually converting data from one type to another using built-in methods. Example 1: Convert to Number Explicitly
let result;
result = Number('324');
console.log(result); // 324
result = Number(true);
console.log(result); // 1
Example 2: Convert to String Explicitly
let result;
result = String(324);
console.log(result); // "324"
result = String(true);
console.log(result); // "true"
Example 3: Convert to Boolean Explicitly
let result;
result = Boolean('');
console.log(result); // false
result = Boolean(324);
console.log(result); // true
Here's a table summarizing the conversion of different values to String, Number, and Boolean in JavaScript:
Value | String Conversion | Number Conversion | Boolean Conversion |
---|---|---|---|
1 | "1" | 1 | true |
0 | "0" | 0 | false |
"1" | "1" | 1 | true |
"0" | "0" | 0 | true |
"ten" | "ten" | NaN | true |
true | "true" | 1 | true |
false | "false" | 0 | false |
null | "null" | 0 | false |
undefined | "undefined" | NaN | false |
'' | "" | 0 | false |
' ' | " " | 0 | true |
Understanding these conversion mechanisms is crucial for writing robust and predictable JavaScript code.