JavaScript Tutorial
JavaScript Typeof
typeof returns a string: "number", "string", "object". Arrays and null both say "object" — check them extra.
A string that names the kind
typeof value is an operator, not a function. It returns a string you can compare. Use it when you need to know whether a name holds a number, a string, a function, or something else before you call a method on it.
Parentheses are optional: typeof x and typeof(x) do the same job. The result is always a string, even when the value is undefined.
The usual answers
| Value | typeof |
|---|---|
42 or NaN | "number" |
"hi" | "string" |
true | "boolean" |
undefined | "undefined" |
| a function | "function" |
an object, array, or null | "object" |
10n | "bigint" |
| a symbol | "symbol" |
Example
console.log(typeof 7);
console.log(typeof "7");
console.log(typeof true);
console.log(typeof undefined);
console.log(typeof console.log);
Click Try it in JavaScript under an example. That opens/javascript/try — a live page and a console.
Arrays say object
An array is an object with a length and indexed slots. typeof [] is"object", not "array". Ask Array.isArray(value) when the difference matters.
Example
const list = [1, 2, 3];
const record = { n: 3 };
console.log(typeof list);
console.log(typeof record);
console.log(Array.isArray(list));
console.log(Array.isArray(record));
null says object
typeof null is "object". That is an old language bug that was never fixed, because fixing it would break existing pages. Treat null as its own check:value === null.
Example
const empty = null;
const box = {};
console.log(typeof empty);
console.log(typeof box);
console.log(empty === null);
console.log(box === null);
If you only test typeof x === "object", you will treat null as a usable object and then crash on x.name.
A safe object check
When you need “a real object I can read fields from,” combine the tests. Arrays may or may not count, depending on the job.
Example
function describe(value) {
if (value === null) return "null";
if (Array.isArray(value)) return "array";
return typeof value;
}
console.log(describe(null));
console.log(describe([1, 2]));
console.log(describe({ a: 1 }));
console.log(describe("hi"));
typeof and missing names
typeof undeclaredName is "undefined" and does not throw. Reading the name without typeof throws ReferenceError. That is one reason people wrap a check in typeof before using a global that might not exist.
For a variable you declared, typeof still returns "undefined" if you have not assigned yet. That is normal, not an error.
What to remember
typeofreturns a string such as"number"or"string".- Arrays and
nullboth report"object". - Use
Array.isArrayand=== nullfor those two cases. - Functions report
"function", which is the useful exception.
Next: type conversion — turning a string into a number on purpose, and how + does it by accident.