2.3 Module 2 · Variables, Data Types & Functions

Type Conversion

Learn how JavaScript transforms values from one type to another — automatically behind the scenes, or explicitly under your control — and how to avoid the surprising bugs that come with it.

1

Definition

Type Conversion in JavaScript is the process of converting a value from one data type to another. It can happen automatically (implicit coercion) or manually (explicit conversion) using built-in functions like Number(), String(), and Boolean().

Understanding type conversion is essential for writing bug-free code — many of JavaScript's most confusing behaviours come from unexpected automatic conversions.

2

Simple Way

Type conversion is like changing the format of data — the value stays similar but the type changes:

→ String 123 becomes "123" — a number turned into text
→ Number "123" becomes 123 — text turned into a usable number
→ Boolean Anything becomes true or false — useful in conditions

JavaScript sometimes converts types on its own (implicit), or you can control it manually (explicit).

3

Code Examples

Example 1 — Implicit Conversion (Automatic)
// + with a string → concatenation
let result1 = "5" + 2;
console.log(result1);       // "52"
console.log(typeof result1);

// - always forces numeric conversion
let result2 = "5" - 2;
console.log(result2);       // 3
console.log(typeof result2);
Output
Click ▶ Run to execute
Explanation
  • "5" + 2+ sees a string so it concatenates: "52"
  • "5" - 2- has no string meaning, so JavaScript converts "5" to a number: 3
  • The operator determines which direction the coercion goes
Example 2 — Explicit Conversion (Manual)
// String → Number
let str = "123";
let num = Number(str);
console.log(num);
console.log(typeof num);

// Number → String
let value = 100;
let text = String(value);
console.log(text);
console.log(typeof text);

// Any value → Boolean
console.log(Boolean(0));    // false
console.log(Boolean(1));    // true
console.log(Boolean(""));   // false
console.log(Boolean("Hi")); // true
Output
Click ▶ Run to execute
Explanation
  • Number() → converts a string to a numeric value
  • String() → converts any value to its text representation
  • Boolean()falsy values (0, "", null, undefined, NaN) become false — everything else is true
Example 3 — Important Edge Cases
console.log(Number("abc")); // NaN — not convertible
console.log(Number(""));    // 0   — empty string = 0
console.log(Number(true));  // 1
console.log(Number(false)); // 0

console.log(Boolean("0"));  // true  — non-empty string
console.log(Boolean(0));    // false — zero is falsy

console.log(isNaN("abc"));  // true  — check for NaN safely
Output
Click ▶ Run — some of these will surprise you!
Explanation
  • NaN (Not a Number) is returned when a string cannot be parsed as a number
  • "0" → Boolean is true because the string is non-empty; 0 → Boolean is false because zero is falsy
  • Use isNaN() to safely test whether a conversion failed
4

Real-Life Example

Think of type conversion like exchanging different formats of the same value:

"100"
₹100 written on a piece of paper — text, not spendable
100
An actual ₹100 note — you can calculate and spend with it
true
A green light — yes, proceed, the condition is met
NaN
A torn receipt — it looks like a number but means nothing
5

HTML + JavaScript Example

Input values from HTML forms are always strings. Click ▶ Preview and try entering an age — watch how Number() converts it before the check runs.

Live in Browser — Age Checker with Type Conversion
<!DOCTYPE html>
<html>
<head><title>Type Conversion</title></head>
<body style="font-family:sans-serif;padding:24px;background:#f8f9fa">

  <h2>Age Checker</h2>
  <input id="ageInput" type="text" placeholder="Enter your age"
    style="padding:8px 12px;border:1px solid #ccc;border-radius:6px;font-size:1rem">
  <button onclick="checkAge()"
    style="margin-left:8px;padding:8px 18px;background:#f7df1e;border:none;
           border-radius:6px;cursor:pointer;font-weight:700;font-size:1rem">
    Submit
  </button>
  <div id="output" style="margin-top:16px;line-height:2;font-size:0.95rem"></div>

  <script>
    function checkAge() {
      let raw = document.getElementById("ageInput").value;
      let age = Number(raw); // explicit conversion

      let out = document.getElementById("output");

      if (isNaN(age) || raw === "") {
        out.innerHTML = "<b style='color:red'>Please enter a valid number.</b>";
        return;
      }

      out.innerHTML =
        "<b>Raw input type:</b> " + typeof raw + "<br>" +
        "<b>Converted type:</b> " + typeof age + "<br>" +
        "<b>Result:</b> " + (age >= 18 ? "✅ Adult" : "❌ Minor");
    }
  </script>

</body>
</html>
Live Preview
6

Tasks (Practice)

Easy Task 1 — Before & after conversion
Starter code
let str = "50";
  • Print typeof str before conversion
  • Convert str to a number using Number()
  • Print typeof again to confirm the change
Medium Task 2 — Total price calculator
Starter code
let price    = "200"; // comes from a form input
let quantity = 3;
  • Convert price to a number using Number()
  • Multiply by quantity to get the total
  • Print "Total: 600" — confirm it's a number, not "200200200"
7

MCQs

Q1
What is the output?
console.log("10" + 5);
Output
Run it to verify
  • A 15
  • B "15"
  • C "105"
  • D Error
💡 C is correct. When + sees a string operand, it concatenates instead of adding. The number 5 is coerced to "5", giving "105".
Q2
What is the output?
console.log("10" - 5);
Output
Run it to verify
  • A "105"
  • B 5
  • C NaN
  • D Error
💡 B is correct. The - operator has no string meaning, so JavaScript converts "10" to the number 10 automatically. 10 - 5 = 5.
Q3
Which of these returns false?
console.log(Boolean(1));
console.log(Boolean("Hello"));
console.log(Boolean(0));
console.log(Boolean("123"));
Output
Run it to verify
  • A Boolean(1)
  • B Boolean("Hello")
  • C Boolean(0)
  • D Boolean("123")
💡 C is correct. 0 is one of JavaScript's six falsy values. The others are "", null, undefined, NaN, and false itself. Everything else is truthy.
8

Pro Tips & Extra Knowledge

  • 01

    Always use === (strict equality) instead of == — loose equality silently converts types and causes bugs:

    == vs ===
    console.log(5 == "5");  // true  — type converted, values match
    console.log(5 === "5"); // false — different types, no conversion
    console.log(0 == false);  // true  — coercion!
    console.log(0 === false); // false — strict, no coercion
    Output
    Click ▶ Run to execute
  • 02

    Watch out for Number("") and Number(" ") — both return 0, not NaN, which can hide empty-input bugs:

    Empty string conversion trap
    console.log(Number(""));   // 0 — not NaN!
    console.log(Number(" "));  // 0 — whitespace also becomes 0
    console.log(Number("abc")); // NaN — truly invalid
    
    // Safe pattern: check for empty before converting
    let input = "";
    if (input === "") {
      console.log("Input is empty");
    } else {
      console.log(Number(input));
    }
    Output
    Click ▶ Run to execute
  • 03

    Use isNaN() to detect a failed conversion — comparing directly to NaN never works because NaN !== NaN:

    Detecting NaN correctly
    let result = Number("abc");
    
    console.log(result);          // NaN
    console.log(result === NaN);  // false — NaN is never equal to itself!
    console.log(isNaN(result));   // true  — correct way to check
    Output
    Click ▶ Run to execute
  • 04

    The six falsy values in JavaScript — memorise these and you'll never be surprised by a Boolean conversion again:

    All six falsy values
    console.log(Boolean(false));     // false
    console.log(Boolean(0));         // false
    console.log(Boolean(""));        // false
    console.log(Boolean(null));      // false
    console.log(Boolean(undefined)); // false
    console.log(Boolean(NaN));       // false
    // Everything else → true
    Output
    Click ▶ Run to execute
Mini Challenge

Two operations, same variables — but the operator changes everything. Predict both outputs before running.

What does this print?
let a = "10";
let b = 2;

console.log(a * b);
console.log(a + b);
Output
Think first, then run!
Step-by-Step Explanation
// Variables:
//   a = "10"  (string)
//   b = 2     (number)

// Line 1: a * b
//   * has no string meaning → JavaScript converts "10" to 10
//   10 * 2 = 20
//   Output → 20  (number)

// Line 2: a + b
//   + sees "10" is a string → concatenation mode
//   b is converted to "2"
//   "10" + "2" = "102"
//   Output → "102"  (string)

// Key takeaway:
//   * forces numeric conversion — the operator has no string form
//   + is overloaded — it concatenates if either operand is a string
//
//   Fix: always convert before operating
//   console.log(Number(a) + b); // 12 — correct addition