Type coercion in JavaScript is the process of automatically or manually converting one data type into another during certain operations.
Type coercion in JavaScript can happen in two ways:
- Implicit Coercion
- Explicit Coercion
Implicit coercion happens when JavaScript automatically converts one data type into another during an operation.
Note: This conversion happens without explicit instruction from the developer.
// String Coercion
let result = 10 + "5"; // Number → String
console.log(result); // "105"
console.log(typeof result); // stringNote: The
+operator performs string concatenation when one operand is a string.
// Numeric Coercion
let result = 10 - "5"; // String → Number
console.log(result); // 5
console.log(typeof result); // numberNote: Arithmetic operators like
-,*, and/force numeric conversion.
// Boolean Coercion
if (1) {
console.log("This runs");
}Note:
1is implicitly converted totrueduring condition evaluation.
Explicit coercion happens when you manually convert a value from one type to another using built-in JavaScript methods.
Note: This approach makes your code clearer and more predictable.
// Explicit Conversion to Number
let value = "10";
let result = Number(value);
console.log(result); // 10
console.log(typeof result); // number// Explicit Conversion to String
let valueTwo = 100;
let resultTwo = String(valueTwo);
console.log(resultTwo); // "100"
console.log(typeof resultTwo); // string// Explicit Conversion to Boolean
console.log(Boolean(1)); // true
console.log(Boolean(0)); // falseNote: Explicit coercion does not always produce the expected result.
console.log(Number("10px")); // NaN