Seven primitive types plus objects. Values have types; variables do not.
The eight types
| Type | Examples | typeof |
|---|---|---|
| Number | 42, 3.14, -0, NaN, Infinity | "number" |
| BigInt | 9007199254740993n | "bigint" |
| String | 'hi', "hi", template literals with backticks | "string" |
| Boolean | true, false | "boolean" |
| Undefined | undefined — declared but no value | "undefined" |
| Null | null — intentional “no value” | "object" (historic bug!) |
| Symbol | Symbol('id') — unique key | "symbol" |
| Object | {}, [], functions, dates, maps… | "object" / "function" |
typeof in practice
console.log(typeof 42, typeof 10n, typeof "s", typeof true);
console.log(typeof undefined, typeof Symbol(), typeof {}, typeof []);
console.log(typeof null); // the famous bug
console.log(typeof function () {}, typeof class {});
console.log(typeof notDeclaredAnywhere); // no ReferenceErrornumber bigint string boolean
undefined symbol object object
object
function function
undefinedChecking types reliably
| Question | Use |
|---|---|
| Is it an array? | Array.isArray(x) (not typeof) |
| Is it null? | x === null |
| Null or undefined? | x == null (the one accepted use of ==) or x ?? fallback |
| Instance of a class? | x instanceof Date (walks the prototype chain) |
| Exact built-in tag? | Object.prototype.toString.call(x) |
| Is it NaN? | Number.isNaN(x) |
const tag = (x) => Object.prototype.toString.call(x);
console.log(Array.isArray([]), [] instanceof Array);
console.log(tag(null), tag([]), tag(new Date(0)), tag(/re/));true true
[object Null] [object Array] [object Date] [object RegExp]undefined vs null
let a;
const obj = {};
function f() {}
console.log(a, obj.missing, f());
console.log(null == undefined, null === undefined);
console.log(Number(null), Number(undefined));undefined undefined undefined
true false
0 NaNDynamic typing
let value = 10;
console.log(typeof value);
value = "ten";
console.log(typeof value);
value = [10];
console.log(typeof value, Array.isArray(value));number
string
object trueHow many data types does JavaScript have?
Why does typeof null return "object"?