JavaScript Type Conversion

In JavaScript, values can be converted from one data type to another either automatically (type coercion) or manually (type casting). This process is known as type conversion.


Implicit Type Conversion (Type Coercion)

JavaScript automatically converts data types when needed. This is known as type coercion.

let result = "5" + 2;
console.log(result);  // "52" (number 2 is converted to a string)

Here, JavaScript converts the number 2 to a string and performs string concatenation.

let result = "5" - 2;
console.log(result);  // 3 (string "5" is converted to number)

In above case, the – operator forces both operands to be treated as numbers.


Explicit Type Conversion (Type Casting)

You can manually convert values using built-in functions.

Convert to String

String(123);            // "123"
(123).toString();       // "123"

Convert to Number

Number("123");          // 123
parseInt("123.45");     // 123
parseFloat("123.45");   // 123.45


You can also use parseInt() or parseFloat():

let price = "99.50";
console.log(parseInt(price));   // 99
console.log(parseFloat(price)); // 99.5

Convert to Boolean

Boolean(1);             // true
Boolean(0);             // false
Boolean("");            // false
Boolean("hello");       // true


Values like false, 0, “”, null, undefined, and NaN are considered falsy. All others are truthy.


Summary

OperationResultExplanation
“5” + 2“52”Number converted to string
“5” – 23String converted to number
true + 12true becomes 1
Number(“123.45”)123.45String to number
Boolean(“”)falseEmpty string is falsy
Boolean(“hello”)trueNon-empty string is truthy

Why Type Conversion Matters

  • It prevents unexpected behavior in your code
  • It helps in handling form inputs (which are strings)
  • It’s essential for proper comparisons and calculations

Best Practices

  • Avoid relying on implicit conversion in important logic.
  • Prefer explicit conversion to make code clear and bug-free.
  • Use === instead of == to avoid unintended type coercion.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.