*
Previous Numbers & Math Object in JavaScript JavaScript-Conditionals Next

Type Conversion & Coercion in JavaScript

πŸ“˜ Type Conversion & Coercion in JavaScript

Let’s carefully unpack Type Conversion and Type Coercion in JavaScript. These two concepts often confuse beginners, but once you see the difference with examples, it becomes crystal clear.

1️⃣ Type Conversion (Explicit Casting)

Type Conversion means manually converting a value from one type to another using built-in functions. Also called type casting.

// String to Number
let str = "123";
let num = Number(str);
console.log(num);        // 123
console.log(typeof num); // number

// Number to String
let n = 42;
let s = String(n);
console.log(s);          // "42"
console.log(typeof s);   // string

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

// Boolean to String
console.log(String(true));  // "true"
  

2️⃣ Type Coercion (Implicit Conversion)

Type Coercion means JavaScript automatically converts one type to another during operations. This is implicit and sometimes leads to unexpected results.

// String + Number β†’ String
console.log("5" + 2);   // "52"

// String - Number β†’ Number
console.log("5" - 2);   // 3

// Boolean + Number β†’ Number
console.log(true + 1);  // 2

// Loose equality (==) does coercion
console.log(5 == "5");  // true

// Strict equality (===) avoids coercion
console.log(5 === "5"); // false
  

3️⃣ Special Cases

console.log(Number(""));        // 0
console.log(Number("abc"));     // NaN
console.log(Number(null));      // 0
console.log(Number(undefined)); // NaN

if ("") console.log("truthy"); else console.log("falsy"); 
// Output: falsy ("" coerces to false)
  

4️⃣ Quick Recap

  • Type Conversion β†’ Explicit, done by developer (Number(), String(), Boolean()).
  • Type Coercion β†’ Implicit, done automatically by JS during operations.
  • == allows coercion, === avoids it (always prefer ===).
  • Be careful with coercion, as it can produce surprising results.

🧠 Key Rules

  • String concatenation with + converts non-string to string.
  • Arithmetic operations (-, *, /, %) convert strings to numbers.
  • Boolean values are converted to numbers in arithmetic: true β†’ 1, false β†’ 0.
  • Be careful: implicit coercion can lead to unexpected bugs.

✨ Best Practices

  • Prefer explicit type conversion using Number(), String(), Boolean().
  • Be cautious with + operator, as it can trigger string concatenation.
  • Understand implicit coercion to avoid unexpected results in expressions.

πŸ“˜ Truthy vs Falsy values in JavaScript

1️⃣ Falsy Values

These values convert to false in Boolean context:

Value Boolean() Notes
false false Boolean false itself
0 false Zero
-0 false Negative zero
0n false BigInt zero
"" false Empty string
null false Null value
undefined false Undefined value
NaN false Not-a-Number

2️⃣ Truthy Values

Everything else is considered true in Boolean context:

  • Non-zero numbers (e.g., 42, -7)
  • Non-empty strings (e.g., "hello", "0", "false")
  • Objects (e.g., {}, [])
  • Functions
  • Dates
  • Infinity and -Infinity

3️⃣ Examples

console.log(Boolean(""));       // false
console.log(Boolean("hello"));  // true
console.log(Boolean(0));        // false
console.log(Boolean(123));      // true
console.log(Boolean(null));     // false
console.log(Boolean({}));       // true
console.log(Boolean([]));       // true
  

βœ… Quick Recap

  • Only 8 values are falsy: false, 0, -0, 0n, "", null, undefined, NaN.
  • Everything else is truthy.
  • Truthy/falsy is important in if conditions and logical operations.

πŸ“Œ Mini Project: Simple Calculator

This mini project demonstrates a simple calculator using JavaScript in the browser console.

βœ… Example Code:

// Prompt user for input
let num1 = Number(prompt("Enter the first number:"));
let operator = prompt("Enter an operator (+, -, *, /):");
let num2 = Number(prompt("Enter the second number:"));

let result;

// Perform calculation based on operator
if(operator === "+") {
  result = num1 + num2;
} else if(operator === "-") {
  result = num1 - num2;
} else if(operator === "*") {
  result = num1 * num2;
} else if(operator === "/") {
  if(num2 !== 0) {
    result = num1 / num2;
  } else {
    result = "Error: Division by zero";
  }
} else {
  result = "Invalid operator";
}

console.log(`Result: ${result}`);

🎯 How it Works:

  1. Prompts the user to enter two numbers and an operator.
  2. Performs the calculation based on the chosen operator.
  3. Displays the result in the console.

Try saving this code in a script.js file or directly in the browser console and test it with different numbers and operators.

Back to Index
Previous Numbers & Math Object in JavaScript JavaScript-Conditionals Next
*
*