IT Course JavaScript Basics 039_Type Conversion
Type conversion is the process of converting one data type to another. Type conversion can be implicit (automatically done by the JavaScript engine) or explicit (manually converted through coding).
Implicit Type Conversion (Type Coercion)
In some operations, JavaScript automatically performs type conversion to perform arithmetic or comparison.
Example:
let num = 5 + "5";console.log(num); // Output "55", when adding a number and a string, the number is converted to a stringExplicit Type Conversion
String Conversion
String() function: Converts other types to strings.
Example:
let num = 123;let str1 = String(num); // String() function, can handle `null` or `undefined`let str2 = num.toString(); // toString() method, cannot handle `null` or `undefined`let str3 = num + ""; // By adding an empty string, get implicit type conversion to stringconsole.log(str1); // Output "123"console.log(str2); // Output "123"console.log(str3); // Output "123"Number Conversion
Number() function: Converts other types to numbers.
Example:
let str1 = "123";let str2 = "";let str3 = "aaa";let num1 = Number(str1);let num2 = Number(str2);let num3 = Number(str3);let num4 = +str1;console.log(num1); // Output 123console.log(num2); // Output 0console.log(num3); // Output NaNconsole.log(num3); // Output 123, if using - sign, output -123Note: If the string cannot be parsed as a valid number, the result will be NaN (Not a Number).
parseInt() and parseFloat() functions: Convert strings to integers or floating-point numbers.
Example:
let str = "42";let num = parseInt(str);console.log(num); // Output 42
let str = "3.14";let num = parseFloat(str);console.log(num); // Output 3.14Boolean Conversion
Boolean() function: Converts other types to boolean values.
Example:
let value = "Hello";let bool1 = Boolean(value);let bool2 = !value;console.log(bool1); // Output true, non-empty string converts to trueconsole.log(bool2); // Output true, use logical NOT for implicit conversion of non-boolean values (! value is false, then use !! to get positive)Note: 0, NaN, null, undefined, empty string, etc. (empty, non-existent, false) will convert to false, other values and objects will convert to true.