JavaScript Reference ยท Practical Pages
Data types and type conversion
Concept page on JavaScript data types: the seven primitives, objects, typeof results, and the rules for explicit and implicit conversion to string, number and boolean.
Every JavaScript value is either a primitive or an object. There are seven primitive types, and everything else (arrays, functions, dates, maps, regular expressions, class instances) is an object. Variables have no types; values do, so the same variable can hold a number now and a string later.
Operators and built-in functions convert values between types, sometimes because you ask for it (explicit conversion) and sometimes silently (implicit conversion, also called coercion). Knowing the rules removes most "why is this NaN?" surprises.
The types
| Type | Example | typeof |
|---|---|---|
| Undefined | undefined |
"undefined" |
| Null | null |
"object" (a historical mistake that cannot be fixed) |
| Boolean | true, false |
"boolean" |
| Number | 42, 3.14, NaN, Infinity |
"number" |
| BigInt | 123n |
"bigint" |
| String | "hi" |
"string" |
| Symbol | Symbol("id") |
"symbol" |
| Object | {}, [], new Date() |
"object" |
| Function | () => {} |
"function" (an object that can be called) |
Press Run (or Ctrl + Enter) to see the console output here.
No output.
typeof cannot tell arrays, dates or null apart from plain objects. Use Array.isArray(), instanceof, or an explicit === null check for those.
Primitives are immutable and compared by value
Strings, numbers and the other primitives cannot be changed in place: "abc".toUpperCase() returns a new string. Two primitives are equal when their values are equal. Objects are compared by identity: two separate {} are never ===, even when they look the same.
Explicit conversion
The functions String(), Number() and Boolean() (called without new) convert on purpose.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Key rules for Number(value):
- A string is trimmed; an empty or whitespace-only string gives
0; anything not a valid number givesNaN. truegives1,falseandnullgive0,undefinedgivesNaN.- Objects are first converted to a primitive. An array becomes a string (
[5]becomes"5",[1, 2]becomes"1,2") and then a number. - A
BigIntconverts to a number, but aSymbolthrows aTypeError.
parseInt() and parseFloat() read as much of the start of a string as they can and stop at the first character that does not fit; Number() rejects the whole string.
Implicit conversion
Operators convert operands automatically:
+concatenates if either operand is a string (after converting objects to primitives); otherwise it adds numbers.-,*,/,%,**always convert both operands to numbers.==converts when the types differ;===never does. See equality comparison.if,while,!,&&,||,?:convert to boolean; see truthy and falsy values.- Template literals and
String.prototype.concat()convert values to strings.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Converting objects to primitives
When an object meets an operator that wants a primitive, JavaScript calls its Symbol.toPrimitive method if present, otherwise valueOf() and toString() in an order that depends on the hint ("number", "string" or "default"). You can customize it, see Symbol.toPrimitive.
Usage notes
- Prefer explicit conversion.
Number(x)andString(x)document intent;+xand"" + xwork but read as tricks. - Validate numbers with
Number.isNaN()andNumber.isFinite(), which do not coerce, unlike the globalisNaN()andisFinite(). - Numbers are 64-bit floats. Integers are exact up to
Number.MAX_SAFE_INTEGER(2^53 - 1); beyond that useBigInt. Decimal fractions such as0.1 + 0.2are not exact. - BigInt does not mix with Number in arithmetic:
1n + 1throws aTypeError. Convert one side explicitly. nullversusundefined.undefinedmeans "no value was assigned";nullis an intentional empty value.null == undefinedistrue, and they are the only values that are loosely equal to each other and nothing else.- Wrapper objects.
new String("a")creates an object, not a primitive; avoidnewwithString,NumberandBoolean. - Dates convert to strings with
+, but to numbers with-, because their default hint is"string".
Browser support
All data types and conversion rules here are supported everywhere. BigInt and Symbol are in every current browser.
Related
parseInt(),parseFloat(),NaNtypeof, equality comparison- Lessons: Data types, Type conversion