Js Type Conversion in JavaScript
? JavaScript Type Conversion
JavaScript is a dynamically typed language, which means it automatically converts values between types when needed. This is called type conversion or type coercion.
1. Type Conversion Types
a) Implicit Conversion (Coercion)
JavaScript automatically converts types in certain operations.
Example:
console.log('5' + 3); // "53" (number 3 converted to string)console.log('5' - 3); // 2 (string '5' converted to number)console.log('5' * '2'); // 10 (both strings converted to numbers)b) Explicit Conversion
You manually convert types using functions or methods:
Convert to Number:
Number(),parseInt(),parseFloat()Convert to String:
String(),.toString()Convert to Boolean:
Boolean()
2. Common Type Conversions
a) String to Number
Number("123"); // 123 (number)parseInt("123px"); // 123 (integer, stops at first non-digit)parseFloat("12.34"); // 12.34 (float)b) Number to String
String(123); // "123"(123).toString(); // "123"c) Any to Boolean
Boolean(0); // falseBoolean(1); // trueBoolean(""); // falseBoolean("abc"); // true3. Truthy and Falsy Values
In JavaScript, some values are treated as false when converted to boolean:
Falsy values:
false,0,-0,""(empty string),null,undefined,NaNEverything else is truthy.
if ("") { console.log("Won't run");} else { console.log("Empty string is falsy");}4. Examples
console.log(Number("123")); // 123console.log(String(456)); // "456"console.log(Boolean(0)); // falseconsole.log(Boolean("text")); // trueconsole.log('5' + 3); // "53" (number to string)console.log('5' - 3); // 2 (string to number)5. Avoid Confusing Coercions
Explicit conversion is usually better to avoid unexpected bugs:
let val = "10";let num = Number(val); // explicit conversionconsole.log(num + 5); // 15 (number addition)If you want, I can give examples on how type coercion behaves in tricky scenarios or how to handle conversions safely!