References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript typeof operator

Operator JavaScript All modern browsers Updated
Quick answer

The typeof operator returns a string describing a value's type — "string", "number", "boolean", "function", "undefined", "object" and more. typeof "hi" is "string". Watch the famous quirk: typeof null is "object", not "null".

Overview

typeof tells you what kind of value you're holding, as a string. It's a unary operator — you put it before a value or variable, with no parentheses needed (though typeof(x) also works). It returns one of a small set of strings: "string", "number", "bigint", "boolean", "undefined", "symbol", "function" or "object".

It's most useful for guarding against missing or wrong-typed values: if (typeof x === "undefined") safely checks for an undeclared variable without throwing, and if (typeof cb === "function") confirms a callback before calling it.

Two well-known quirks to remember. typeof null returns "object" — a famous, never-fixed bug in the language — so don't use typeof to test for null; compare directly with === null instead. And arrays also report as "object", so to detect an array use Array.isArray(), not typeof. For checking which class an object came from, see instanceof.

Syntax

typeof value

typeof "hi"      // "string"
typeof 42        // "number"
typeof undefined // "undefined"
typeof null      // "object"  (quirk!)
typeof []        // "object"  (use Array.isArray)

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  const values = ['hi', 42, true, undefined, null, []];

  const lines = values.map(v => {
    const label = Array.isArray(v) ? 'array' : typeof v;
    return JSON.stringify(v) + ' -> ' + label;
  });

  document.getElementById('out').textContent = lines.join('\n');
</script>

Best practices

  • Use typeof x === "undefined" to safely check for undeclared or undefined values.
  • Check callbacks with typeof fn === "function" before calling them.
  • Don't use typeof for null — it returns "object". Compare with === null.
  • Detect arrays with Array.isArray(), since typeof [] is "object".

Frequently asked questions

What does typeof return for null?
"object" — a long-standing quirk in JavaScript. To check for null, use value === null instead.
How do I check the type of a variable in JavaScript?
Use typeof value, which returns a string like "string" or "number".
Why does typeof an array return "object"?
Arrays are objects in JavaScript. To specifically detect an array, use Array.isArray(value).
What is the difference between typeof and instanceof?
typeof returns a primitive type name as a string; instanceof checks whether an object was created from a particular constructor or class.