Spex3
    

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)

📌 Note: The + operator prefers string concatenation over arithmetic.

✅ Example: Number Conversion
When mathematical operations (-, *, /) are used, strings are converted to numbers.


console.log("10" - 2); // 8
console.log("6" * 2); // 12
console.log("20" / 4); // 5

📌 Note: The -, *, and / operators prefer numeric conversion.

✅ Example: Boolean Conversion
Falsy values ("", 0, null, undefined, NaN, false) convert to false in boolean contexts.


console.log(Boolean("")); // false
console.log(Boolean(0)); // false
console.log(Boolean(42)); // true
console.log(Boolean("Hi")); // true


2️⃣ Explicit Type Coercion (Manual Conversion)
You can manually convert values using built-in functions like Number(), String(), and Boolean().

✅ 1. Convert to Number (Number())

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

✅ 2. Convert to String (String())


console.log(String(42)); // "42"
console.log(String(true)); // "true"
console.log(String(null)); // "null"
console.log(String(undefined));// "undefined"

✅ 3. Convert to Boolean (Boolean())


console.log(Boolean(1)); // true
console.log(Boolean(0)); // false
console.log(Boolean("")); // false
console.log(Boolean("hello"));// true
console.log(Boolean(null)); // false


3️⃣ Type Coercion in Comparisons
✅ Loose Equality (==) vs. Strict Equality (===)
The == operator performs type coercion, while === checks both value and type.


console.log(5 == "5"); // true (because "5" is converted to a number)
console.log(5 === "5"); // false (because types are different)


📌 Best Practice: Use === to avoid unintended type coercion.

🎯 Summary: Best Practices
✅ Be aware that JavaScript automatically converts types in operations.
✅ Use explicit conversions (Number(), String(), Boolean()) for clarity.
✅ Prefer === over == to avoid unintended type coercion.


    Date: 2025-03-29 00:00:00.000000