Type Coercion in JavaScript 🔄

Type Coercion in JavaScript 🔄
What is Type Coercion?
Type coercion is the automatic conversion of data types in JavaScript when different types are operated together. It happens in two ways:
Implicit Coercion (automatic conversion by JavaScript)
Explicit Coercion (manual conversion by developers)
1️⃣ Implicit Type Coercion (Automatic Conversion)
JavaScript automatically converts one data type to another when needed.
✅ Example: String Conversion
When a number is added to a string, JavaScript converts the number to a string.
console.log("Hello " + 5); // "Hello 5"
console.log("5" + 5); // "55" (number 5 becomes a string)
console.log("10" - 2); // 8
console.log("6" * 2); // 12
console.log("20" / 4); // 5
console.log(Boolean("")); // false
console.log(Boolean(0)); // false
console.log(Boolean(42)); // true
console.log(Boolean("Hi")); // true
console.log(Number("42")); // 42
console.log(Number("3.14")); // 3.14
console.log(Number("hello"));// NaN (Not a Number)
console.log(Number(true)); // 1
console.log(Number(false)); // 0
console.log(String(42)); // "42"
console.log(String(true)); // "true"
console.log(String(null)); // "null"
console.log(String(undefined));// "undefined"
console.log(Boolean(1)); // true
console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean("hello"));// true
console.log(Boolean(null)); // false
console.log(5 == "5"); // true (because "5" is converted to a number)
console.log(5 === "5"); // false (because types are different)
Date: 2025-03-29 00:00:00.000000