π JavaScript typeof Operator β Know What You're Dealing With

Ever wanted to know what kind of value a variable holds in JavaScript?
Thatβs where the typeof
operator comes in. It tells you the type of any value or variable.
But... sometimes it lies. π
Letβs break it all down: what typeof
gives you, whatβs true, whatβs weird, and how to handle it.
β The Syntax
typeof value
Returns a string describing the type of the value.
π’ 1. Numbers
console.log(typeof 42); // "number"
console.log(typeof 3.14); // "number"
console.log(typeof NaN); // "number" β yes, still a number
β
Includes both integers, floats, and NaN
.
π€ 2. Strings
console.log(typeof 'hello'); // "string"
console.log(typeof ""); // "string"
console.log(typeof `template`); // "string"
β Works with single, double, and backtick quotes.
βοΈ 3. Booleans
console.log(typeof true); // "boolean"
console.log(typeof false); // "boolean"
β Straightforward.
β 4. Undefined
let x;
console.log(typeof x); // "undefined"
console.log(typeof undefined); // "undefined"
β Default for uninitialized variables.
π« 5. Null (𧨠Surprise!)
console.log(typeof null); // "object" β (bug in JS since 1995)
π§ Even though it says "object"
, null
is not an object.
β To detect null properly:
value === null;
π¦ 6. Objects
console.log(typeof {}); // "object"
console.log(typeof { name: "JS" }); // "object"
β
Basic objects return "object"
.
π 7. Arrays (still objects!)
console.log(typeof [1, 2, 3]); // "object" β
Array.isArray([1, 2, 3]); // true β
typeof
can't distinguish arrays from objects. Use Array.isArray()
instead.
π οΈ 8. Functions
function greet() {}
const arrow = () => {};
console.log(typeof greet); // "function"
console.log(typeof arrow); // "function"
β
The only case where typeof
returns "function"
β everything else is "object"
or primitives.
π£ 9. Symbols
const sym = Symbol('id');
console.log(typeof sym); // "symbol"
β Unique and immutable β often used as keys.
π’ 10. BigInt
const big = 1234567890123456789012345678901234567890n;
console.log(typeof big); // "bigint"
β
For numbers larger than Number.MAX_SAFE_INTEGER
.
π Summary Table
Value/Type | typeof result |
42 , NaN | "number" |
'hello' , `` | "string" |
true , false | "boolean" |
undefined | "undefined" |
null | "object" β |
{} | "object" |
[] | "object" β |
function() {} | "function" β
|
Symbol('id') | "symbol" |
123n | "bigint" |
π§ͺ Bonus: typeof vs constructor vs Array.isArray()
Check | Works For | Use When |
typeof | Primitives, functions | Quick check |
Array.isArray(val) | Arrays | Array detection |
val.constructor.name | Any object | Get class name |
val instanceof Class | Custom types | Inheritance checking |
β Final Thoughts
Use
typeof
for primitive types.Use
Array.isArray()
for arrays.Don't trust
typeof null
β it lies.For more complex type checks, use
constructor
orinstanceof
.
Subscribe to my newsletter
Read articles from pushpesh kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
