JavaScript will often convert values from one type to another automatically — this is called type coercion, and it happens constantly, sometimes in ways that surprise even experienced developers. You can also convert types yourself on purpose, which is called explicit conversion. Understanding both is essential for avoiding bugs that only show up with certain input values.

Explicit Type Conversion

When you want full control, JavaScript gives you built-in functions to convert a value to a specific type:

console.log(Number("42"));     // 42 (number)
console.log(Number("abc"));    // NaN — "Not a Number"
console.log(String(42));        // "42" (string)
console.log(Boolean(0));        // false
console.log(Boolean("hello"));  // true

Output:

42
NaN
42
false
true

Converting a non-numeric string with Number() gives you NaN, not an error — which means a bad conversion can silently propagate through your program unless you check for it with isNaN() or Number.isNaN().

Implicit Coercion (The Gotchas)

JavaScript's + operator behaves differently depending on the operand types — this is the single most common source of coercion confusion:

console.log("5" + 3);   // "53" — number is converted to a string, then concatenated
console.log("5" - 3);   // 2   — string is converted to a number for subtraction
console.log("5" * "2"); // 10  — both strings converted to numbers
console.log(1 + true);   // 2   — true becomes 1
console.log(1 + null);   // 1   — null becomes 0
console.log(1 + undefined); // NaN — undefined can't become a meaningful number

Output:

53
2
10
2
1
NaN

The rule to remember: + prefers string concatenation if either side is a string, while every other arithmetic operator (-, *, /) tries to convert both sides to numbers first.

Common Pitfall: User Input

Values from HTML form fields and prompt() always arrive as strings, even if they look like numbers — so forgetting to convert them before doing math is a frequent beginner bug:

// Imagine this came from an input field
let userInput = "10";

console.log(userInput + 5);          // "105" — wrong! string concatenation
console.log(Number(userInput) + 5);  // 15 — correct, explicitly converted first

Output:

105
15

To sidestep implicit coercion bugs entirely, it helps to get comfortable with the strict equality operator (===), which — unlike == — never coerces types when comparing two values.