JS TypeOf
JavaScript typeof: Inspecting Value Types and Edge Cases
The JavaScript typeof operator returns a lowercase string describing the data type of an expression or variable. It helps you guard function inputs and check whether a global API exists without throwing a ReferenceError.
Complete typeof Return Values
Know these eight possible string results from typeof:
"string","number","boolean","bigint","symbol","undefined": Returned for those six primitive types."function": Returned for functions and ES6classconstructors."object": Returned for plain objects, arrays,Date,RegExp,Map,Set, and notoriouslynull.
Safe Type Checking Example
Because typeof null returns "object" and typeof [1, 2] also returns "object", pair typeof with explicit === null and Array.isArray() checks.
function describeValue(value) {
if (value === null) return "null";
if (Array.isArray(value)) return "array";
if (typeof value === "number" && Number.isNaN(value)) return "NaN";
return typeof value;
}
console.log(describeValue(null)); // "null"
console.log(describeValue([1, 2, 3])); // "array"
console.log(describeValue(Number("abc"))); // "NaN"
console.log(describeValue(() => {})); // "function"
console.log(describeValue(42n)); // "bigint"
Common Mistakes to Avoid
- Checking
typeof val === "object"without excludingnull: Passingnullpasses that check and crashes when you readval.name. Always writeval !== null && typeof val === "object". - Using
typeofto tell arrays apart from objects:typeof []is"object"; always callArray.isArray(val). - Using
typeofon an uninitializedletvariable before its line: Callingtypeof xon an undeclared global returns"undefined", yet callingtypeof xinside a block abovelet x = 1throws aReferenceErrordue to the Temporal Dead Zone.
Frequently Asked Questions
Why does typeof null return "object" in JavaScript?
It is a famous backward-compatibility bug from the very first 1995 JavaScript engine, where both objects and null shared a zero type tag. Changing it today would break millions of legacy websites.
What does typeof NaN return?
typeof NaN returns "number" because NaN belongs to the IEEE 754 floating-point number specification. Check Number.isNaN(val) to catch NaN.
What does typeof return for an ES6 class?
Classes in JavaScript are syntactic sugar over constructor functions, so typeof MyClass returns "function".
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.
Test Your Knowledge
You've completed this section! Take a quick 5-question quiz to check your understanding.