JavaScript Type Conversion

JavaScript provides ways to convert data from one type to another, which is known as type conversion. There are two main types of type conversion: implicit (type coercion) and explicit (type casting).

1. Implicit Conversion (Type Coercion)

JavaScript automatically converts types when it expects a certain type in an operation.

Examples:

  • String Concatenation:
    let result = "5" + 2;  // "52" (Number 2 is converted to a String)
    

    Try It Now

  • Numeric Operations:
    let result = "5" - 2;  // 3 (String "5" is converted to a Number)
    

    Try It Now

  • Boolean Contexts:
    if ("") {
      console.log("This won't log"); // Empty string is coerced to false
    }
    

    Try It Now

2. Explicit Conversion (Type Casting)

You can explicitly convert types using various methods.

2.1 Converting to String

  • Using String():
    let num = 123;
    let str = String(num); // "123"
    

    Try It Now

  • Using .toString():
    let bool = true;
    let str = bool.toString(); // "true"
    

    Try It Now

2.2 Converting to Number

  • Using Number():
    let str = "123";
    let num = Number(str); // 123
    

    Try It Now

  • Using parseInt() and parseFloat():
    let strInt = "123";
    let strFloat = "123.45";
    let intNum = parseInt(strInt);    // 123
    let floatNum = parseFloat(strFloat); // 123.45
    

    Try It Now

2.3 Converting to Boolean

  • Using Boolean():
    let val = 0;
    let bool = Boolean(val); // false
    

    Try It Now

3. Common Conversion Scenarios

3.1 String to Number:

let str = "456";
let num = +str;  // 456 (Unary plus converts string to number)

Try It Now

3.2 Number to String:

let num = 789;
let str = num + ""; // "789" (Concatenation converts number to string)

Try It Now

3.3 Boolean to Number:

let bool = true;
let num = +bool; // 1 (true is converted to 1)

Try It Now

3.4 Falsy to Boolean:

Values like 0, "", null, undefined, NaN, and false are converted to false.

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

Try It Now

Summary

Type conversion in JavaScript can be either implicit or explicit. Understanding how and when to convert types is crucial for writing robust JavaScript code that behaves as expected.