JavaScript Data Types: Primitives, Objects and typeof
Every value in JavaScript has one of eight types. Seven are primitives, simple immutable values: number, string, boolean, undefined, null, bigint and symbol. Everything else, including arrays and functions, is an object. Knowing which is which explains a lot of surprising behavior later.
The primitives
- number covers both integers and decimals; there is no separate integer type. All numbers are 64-bit floating point, so
0.1 + 0.2shows the same rounding error you may know from other languages. Integers are exact up toNumber.MAX_SAFE_INTEGER, about nine quadrillion. - bigint holds integers of any size, written with an
nsuffix:10n. You cannot mix bigint and number in arithmetic without converting. - string is text, in single, double or backtick quotes.
- boolean is
trueorfalse. - undefined means "no value was assigned": a declared but unset variable, a missing property, or a function with no
return. - null means "intentionally empty", set by a programmer.
- symbol creates unique identifiers, mostly used by libraries.
typeof and its quirks
typeof value returns the type as a string. Two results are famous oddities kept for backward compatibility: typeof null is "object", and typeof of a function is "function" even though functions are objects. To test for an array, use Array.isArray(), because typeof [] is just "object".
Expected output
number number string boolean undefined object object object function bigint symbol undefined null 9007199254740991 0.30000000000000004 3.5 Infinity 42 NaN 4
Special numbers
Dividing by zero does not throw; it produces Infinity. An invalid numeric operation produces NaN ("not a number"), which, confusingly, has type number.
Converting text to numbers
Number("42") converts a whole string and returns NaN if any part is not numeric. parseInt("4x") reads digits from the start and stops at the first non-digit, so it returns 4. Use Number() when the input must be entirely numeric and parseInt(text, 10) or parseFloat() when you want leading digits only. Values from form fields and URLs are always strings, so this conversion comes up constantly.
Common mistakes
- Checking
typeof x === "null", which is never true. Compare withx === null. - Assuming
typeof [] === "array". - Forgetting that form input values are strings, so
"2" + 2gives"22".
Summary
- Seven primitive types plus
object; arrays and functions are objects. typeof nullis"object"; useArray.isArray()for arrays.- Numbers are floating point;
NaNandInfinityare numbers too. Number()converts strictly,parseInt()leniently.
Quiz: Data types