H.dev

Type Conversion & Coercion

Changing Data Types

Sometimes in programming, you receive data in one format but need it in another. For example, a user types their age into a form, and it comes to you as a String "25", but you need it to be a Number 25 to do math with it.

Explicit Type Conversion

This is when you manually convert the data from one type to another using JavaScript's built-in functions.

String to Number:

let ageStr = "25";
let ageNum = Number(ageStr);
console.log(typeof ageNum); // "number"

Number to String:

let score = 100;
let scoreStr = String(score);

Implicit Type Coercion

This is where JavaScript gets tricky! If you mix different data types, JavaScript will try to automatically convert (coerce) them behind the scenes to make the operation work.

// The + operator triggers String coercion if one value is a string
let result1 = "5" + 2; 
console.log(result1); // Outputs: "52" (String)

// The - operator triggers Number coercion
let result2 = "5" - 2;
console.log(result2); // Outputs: 3 (Number)

Best Practice: Implicit coercion can lead to unexpected bugs. It is always safer to explicitly convert your types so your code's intention is crystal clear!

💡 Himanshu's Tip:

Whenever you read user input from an HTML form, it always comes back as a String (even if they typed a number like 25). Always explicitly convert it using Number() before doing any math, or you'll end up with weird bugs!

Interview Questions

  1. What is implicit type coercion in JavaScript?
  2. How do you explicitly convert a string to a number?
  3. What happens if you try to subtract a number from a string (e.g., "10" - 5)?

Design & Developed by Himanshu Dubey © 2026