← Back to libraryQuestion 134 of 468
🟨JavaScriptBeginner

JavaScript Data Types and typeof

📌 Definition:

JavaScript has seven primitive types (string, number, boolean, null, undefined, symbol, bigint) and one non-primitive type (object, which includes arrays and functions). typeof returns a string naming the type.

📖 Detailed Explanation:

Primitives are immutable and compared by value; objects are compared by reference. typeof is the operator to inspect a value's type, but it has two famous quirks: typeof null returns 'object' (a long-standing bug kept for compatibility) and typeof of a function returns 'function' even though functions are objects. Arrays also report 'object', so use Array.isArray() to detect arrays. undefined means a variable has been declared but not assigned; null is an intentional 'no value' you assign yourself. NaN is a number that is not equal to itself, so use Number.isNaN() to detect it.

🔑 Key Points:
  • 7 primitives + object; arrays and functions are objects
  • typeof null === 'object' (historical bug)
  • Use Array.isArray() for arrays, Number.isNaN() for NaN
  • undefined = not assigned; null = intentional empty
🌍 Real-World Example:

When asserting on a test-data payload, checking typeof user.roles === 'object' passes for both an array and a plain object — so a bug where roles arrives as {} instead of [] slips through. Array.isArray(user.roles) is the correct, precise check.

🎯 Scenario-Based Interview Question:

What does typeof null return, and how do you reliably check whether a value is an array?