Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Type conversion

Type conversion produces a value of the target type, which can be the same as the input type. Learn the difference between explicit conversion with Number(), String(), and Boolean() and implicit conversion performed by operators.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

Number(value); String(value); Boolean(value)

Type conversion (type conversion) means obtaining a value of the target type. If the input is already of that type, the conversion can return it unchanged: Number(12) returns 12, and Boolean(true) returns true. Conversion is explicit when you call something such as Number(value), String(value), or Boolean(value), or implicit (coercion) when required by an operator or context. It does not change a variable declaration or automatically assign the result back.

The + operator first converts objects to primitive values. If at least one of the resulting values is a string, the operator implicitly converts the other value to a string before concatenating them. If the other value is a Symbol, that implicit conversion throws a TypeError. In contrast, the explicit call String(Symbol("id")) returns "Symbol(id)". If neither value is a string, the operator converts both to numeric values and adds them only if they have the same numeric type. For example, 1n + 1 throws a TypeError because 1n is a BigInt and 1 is a Number. Thus "12" + 3 produces "123", while "12" - 3 produces 9. The === operator does not convert operands to a common type, unlike == in some cases.

Conversion is not validation: Number("") and Number(null) produce 0, whereas Number(undefined) and Number("invalid") produce NaN. Boolean("false") produces true because a nonempty string is truthy. Empty arrays and ordinary objects are also truthy.

Converting objects to numbers or strings can invoke user code through Symbol.toPrimitive, valueOf, or toString and can throw an exception. Call conversion functions without new: new Boolean(false) creates an object that is truthy. The example uses core ECMAScript mechanisms, not Web APIs.

Examples

const text = "12";
const lines = [
  String(Number(text) + 3),
  text + 3,
  String(text - 3),
  String(Boolean("false")),
  String(Number("")),
  String(Number("invalid")),
  String(text === 12)
];
console.log(lines.join("\n"));

Result

15
123
9
true
0
NaN
false

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources