JavaScript provides ways to convert data from one type to another, which is known as type conversion. There are two main types of type conversion: implicit (type coercion) and explicit (type casting).
1. Implicit Conversion (Type Coercion)
JavaScript automatically converts types when it expects a certain type in an operation.
Examples:
- String Concatenation:
let result = "5" + 2; // "52" (Number 2 is converted to a String)
- Numeric Operations:
let result = "5" - 2; // 3 (String "5" is converted to a Number)
- Boolean Contexts:
if ("") { console.log("This won't log"); // Empty string is coerced to false }
2. Explicit Conversion (Type Casting)
You can explicitly convert types using various methods.
2.1 Converting to String
- Using
String()
:let num = 123; let str = String(num); // "123"
- Using
.toString()
:let bool = true; let str = bool.toString(); // "true"
2.2 Converting to Number
- Using
Number()
:let str = "123"; let num = Number(str); // 123
- Using
parseInt()
andparseFloat()
:let strInt = "123"; let strFloat = "123.45"; let intNum = parseInt(strInt); // 123 let floatNum = parseFloat(strFloat); // 123.45
2.3 Converting to Boolean
- Using
Boolean()
:let val = 0; let bool = Boolean(val); // false
3. Common Conversion Scenarios
3.1 String to Number:
let str = "456"; let num = +str; // 456 (Unary plus converts string to number)
3.2 Number to String:
let num = 789; let str = num + ""; // "789" (Concatenation converts number to string)
3.3 Boolean to Number:
let bool = true; let num = +bool; // 1 (true is converted to 1)
3.4 Falsy to Boolean:
Values like 0
, ""
, null
, undefined
, NaN
, and false
are converted to false
.
console.log(Boolean("")); // false console.log(Boolean(0)); // false console.log(Boolean(null)); // false