Skip to content

Latest commit

 

History

History
88 lines (59 loc) · 2.02 KB

File metadata and controls

88 lines (59 loc) · 2.02 KB

06 Type Coercion

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

06.1 Implicit 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.

06.1.1 String Coercion

// String Coercion
let result = 10 + "5"; // Number → String

console.log(result); // "105"
console.log(typeof result); // string

Note: The + operator performs string concatenation when one operand is a string.

06.1.2 Numeric Coercion

// Numeric Coercion
let result = 10 - "5"; // String → Number

console.log(result); // 5
console.log(typeof result); // number

Note: Arithmetic operators like -, *, and / force numeric conversion.

06.1.3 Boolean Coercion

// Boolean Coercion
if (1) {
  console.log("This runs");
}

Note: 1 is implicitly converted to true during condition evaluation.

06.2 Explicit Coercion

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.

06.2.1 Explicit Conversion to Number

// Explicit Conversion to Number
let value = "10";
let result = Number(value);

console.log(result); // 10
console.log(typeof result); // number

06.2.2 Explicit Conversion to String

// Explicit Conversion to String
let valueTwo = 100;
let resultTwo = String(valueTwo);

console.log(resultTwo); // "100"
console.log(typeof resultTwo); // string

06.2.3 Explicit Conversion to Boolean

// Explicit Conversion to Boolean
console.log(Boolean(1)); // true
console.log(Boolean(0)); // false

Note: Explicit coercion does not always produce the expected result. console.log(Number("10px")); // NaN