JavaScript Type Coercion

๐Ÿ“˜ What is Type Coercion?

Type coercion is JavaScript's automatic or implicit conversion of values from one data type to another. This usually happens when JavaScript tries to perform operations on values of different types.

๐Ÿ”„ Implicit Type Coercion

JavaScript automatically converts types when needed.

console.log("5" + 3);  // "53"
console.log("5" - 3);  // 2
console.log("5" * 2);  // 10
console.log("10" / 2); // 5
            
โš ๏ธ The + operator prefers string concatenation.

๐Ÿ”˜ Boolean Type Coercion

Values are converted to true or false in conditions.

Boolean(0);        // false
Boolean(1);        // true
Boolean("");       // false
Boolean("Hello");  // true
Boolean(null);     // false
Boolean(undefined);// false
            

โš–๏ธ Type Coercion with Equality

The == operator performs type coercion, while === does not.

console.log(5 == "5");   // true
console.log(5 === "5"); // false
            
โœ… Always prefer === to avoid unexpected results.

โœ‹ Explicit Type Conversion

Explicit coercion happens when you manually convert types.

Number("10");    // 10
String(100);      // "100"
Boolean(1);       // true
            

๐Ÿงช Try It Yourself

Click the button to see type coercion results: