Syntax
let value = "text"; // string, number, boolean, etc.
typeof value; // "string"Examples
The Primitive Types
Examples of each primitive type and what typeof reports for it.
typeof "hello"; // "string"
typeof 42; // "number"
typeof 3.14; // "number" - no separate float type
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object" - a famous long-standing JS quirk
typeof 10n; // "bigint"
typeof Symbol("id"); // "symbol"
typeof { a: 1 }; // "object"
typeof [1, 2, 3]; // "object" - arrays are objects too
typeof function(){}; // "function"Dynamic Typing
A variable's type can change as new values are assigned to it.
let value = "hello"; // string
value = 42; // now a number
value = true; // now a boolean
value = { a: 1 }; // now an object
// No errors - JavaScript allows this by designBest practices
- Use typeof to check a value's type at runtime, but remember typeof null is "object" due to a long-standing language quirk
- Use Array.isArray() rather than typeof to check specifically for arrays, since typeof reports both as "object"
- Prefer === over == to avoid unexpected type coercion during comparisons
- Consider TypeScript if your project would benefit from catching type mismatches before runtime
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification