What does the typeof operator do and in what format does it return data?

👨‍💻 Frontend Developer 🔴 Rarely Asked 🎚️ Easy
#JavaScript #JS Basics

Quick Answer

The typeof operator determines the data type and returns a string with the type name:

typeof 42;        // "number"
typeof "hello";   // "string"
typeof true;      // "boolean"
typeof undefined; // "undefined"
typeof null;      // "object" (special case!)
typeof NaN;       // "number" (special case!)

Important features:

  • typeof null returns "object" (historical bug)
  • typeof NaN returns "number" (NaN is technically a number)
  • Always returns a string, not the type itself

How typeof Works

Syntax

// As an operator (without parentheses)
typeof value;
 
// As a function (with parentheses)
typeof(value);
 
// Both variants work the same way
console.log(typeof 42);    // "number"
console.log(typeof(42));   // "number"

Return Values

Data Typetypeof ResultExample
Number”number”typeof 42
String”string”typeof "hello"
Boolean”boolean”typeof true
Undefined”undefined”typeof undefined
Symbol”symbol”typeof Symbol()
BigInt”bigint”typeof 123n
Function”function”typeof function(){}
Object”object”typeof {}
Array”object”typeof []
Null”object”typeof null

Usage Examples

Basic Types

// Numbers
console.log(typeof 42);        // "number"
console.log(typeof 3.14);      // "number"
console.log(typeof Infinity);  // "number"
console.log(typeof NaN);       // "number" ⚠️
 
// Strings
console.log(typeof "hello");   // "string"
console.log(typeof 'world');   // "string"
console.log(typeof `template`); // "string"
 
// Boolean type
console.log(typeof true);      // "boolean"
console.log(typeof false);     // "boolean"
 
// Undefined
let x;
console.log(typeof x);         // "undefined"
console.log(typeof undefined); // "undefined"

Special Cases

// null — historical bug!
console.log(typeof null);      // "object" ⚠️
 
// Functions
function greet() { return "Hi!"; }
console.log(typeof greet);     // "function"
 
// Arrow functions
const arrow = () => {};
console.log(typeof arrow);     // "function"
 
// Objects and arrays
console.log(typeof {});        // "object"
console.log(typeof []);        // "object"
console.log(typeof new Date()); // "object"

ES6+ Types

// Symbol (ES6)
const sym = Symbol('id');
console.log(typeof sym);       // "symbol"
 
// BigInt (ES2020)
const big = 123n;
console.log(typeof big);       // "bigint"

Special Cases: null and NaN

typeof null === “object”

This is a historical bug in JavaScript that cannot be fixed:

console.log(typeof null);      // "object" (incorrect!)
console.log(null === null);    // true
console.log(typeof null === "object"); // true
 
// Correct null check
function isNull(value) {
  return value === null;
}
 
// Or check for "emptiness"
function isEmpty(value) {
  return value === null || value === undefined;
}

Why did this happen? In the first version of JavaScript, values were represented as type tag + value. Objects had tag 0, and null was represented as a NULL pointer (0x00), so it got the object tag.

typeof NaN === “number”

NaN (Not a Number) is technically a numeric type:

console.log(typeof NaN);       // "number"
console.log(NaN === NaN);      // false (unique property!)
 
// Correct NaN check
console.log(Number.isNaN(NaN));     // true
console.log(Number.isNaN("hello")); // false
 
// Legacy method (less accurate)
console.log(isNaN(NaN));       // true
console.log(isNaN("hello"));   // true (converts to number!)

Practical Applications

1. Type Checking Before Operations

function safeAdd(a, b) {
  if (typeof a === "number" && typeof b === "number") {
    return a + b;
  }
  throw new Error("Arguments must be numbers");
}
 
console.log(safeAdd(5, 3));    // 8
// safeAdd("5", 3);            // Error

2. Conditional Logic

function processValue(value) {
  switch (typeof value) {
    case "string":
      return value.toUpperCase();
    case "number":
      return value * 2;
    case "boolean":
      return !value;
    case "undefined":
      return "Value is undefined";
    default:
      return "Unknown type";
  }
}
 
console.log(processValue("hello")); // "HELLO"
console.log(processValue(5));       // 10
console.log(processValue(true));    // false

3. Function Parameter Validation

function createUser(name, age, isActive) {
  // Check parameter types
  if (typeof name !== "string") {
    throw new Error("Name must be a string");
  }
  if (typeof age !== "number" || age < 0) {
    throw new Error("Age must be a positive number");
  }
  if (typeof isActive !== "boolean") {
    throw new Error("isActive must be boolean");
  }
  
  return { name, age, isActive };
}

typeof Limitations

1. Doesn’t Distinguish Objects

console.log(typeof {});        // "object"
console.log(typeof []);        // "object"
console.log(typeof null);      // "object"
console.log(typeof new Date()); // "object"
 
// More precise checks
Array.isArray([]);                    // true
value instanceof Date;                // true for dates
Object.prototype.toString.call([]);   // "[object Array]"

2. Doesn’t Work with Undeclared Variables

// This will throw ReferenceError
// console.log(undeclaredVar);
 
// But typeof works!
console.log(typeof undeclaredVar); // "undefined"
 
// Useful for checking global variables existence
if (typeof window !== "undefined") {
  // Browser code
}

typeof Alternatives

1. instanceof

const arr = [];
const date = new Date();
 
console.log(arr instanceof Array);  // true
console.log(date instanceof Date);  // true
console.log(arr instanceof Object); // true (arrays are objects)

2. Object.prototype.toString

function getType(value) {
  return Object.prototype.toString.call(value).slice(8, -1);
}
 
console.log(getType([]));        // "Array"
console.log(getType({}));        // "Object"
console.log(getType(null));      // "Null"
console.log(getType(new Date())); // "Date"

3. Specialized Methods

// For arrays
Array.isArray([]);               // true
 
// For numbers
Number.isNaN(NaN);              // true
Number.isFinite(42);            // true
Number.isInteger(42);           // true
 
// For strings
value instanceof String;        // false for primitives
typeof value === "string";      // true for primitives

Practice Tasks

Task 1

console.log(typeof typeof 42);
Answer "string" — `typeof 42` returns string "number", and `typeof "number"` returns "string".

Task 2

console.log(typeof null);
console.log(typeof undefined);
console.log(typeof NaN);
Answer "object", "undefined", "number" — `null` returns "object" (bug), `undefined` is correct, `NaN` is technically a number.

Task 3

function test() {}
const arrow = () => {};
const obj = { method() {} };
 
console.log(typeof test);
console.log(typeof arrow);
console.log(typeof obj.method);
Answer "function", "function", "function" — all types of functions return "function".

Task 4

let x;
console.log(typeof x);
console.log(typeof y);
Answer "undefined", "undefined" — declared but uninitialized variable and undeclared variable give the same result with `typeof`.

Task 5

console.log(typeof [1, 2, 3]);
console.log(typeof { length: 3 });
console.log(Array.isArray([1, 2, 3]));
console.log(Array.isArray({ length: 3 }));
Answer "object", "object", `true`, `false` — `typeof` doesn't distinguish arrays and objects, need `Array.isArray()`.

Task 6

const sym1 = Symbol("test");
const sym2 = Symbol("test");
const big = 123n;
 
console.log(typeof sym1);
console.log(typeof big);
console.log(sym1 === sym2);
Answer "symbol", "bigint", `false` — new ES6+ types are correctly identified, symbols are always unique.

Practical Tips

1. Remember Special Cases

// Bad — doesn't account for quirks
if (typeof value === "object") {
  // Will trigger for null, arrays, dates...
}
 
// Good — precise check
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
  // Only for plain objects
}

2. Use for Primitive Type Checking

// Excellent for primitive types
if (typeof str === "string") { /* ... */ }
if (typeof num === "number" && !Number.isNaN(num)) { /* ... */ }
if (typeof bool === "boolean") { /* ... */ }

3. Combine with Other Methods

function getDetailedType(value) {
  const type = typeof value;
  
  if (type === "object") {
    if (value === null) return "null";
    if (Array.isArray(value)) return "array";
    if (value instanceof Date) return "date";
    return "object";
  }
  
  return type;
}

Summary

  • typeof returns a string with the data type name
  • Special cases: typeof null === "object", typeof NaN === "number"
  • Works excellently for primitive types
  • Limited for distinguishing objects (arrays, dates, null)
  • Safe for undeclared variables
  • Combine with Array.isArray(), instanceof for accuracy

The typeof operator is a basic tool for type checking in JavaScript. Knowing its quirks will help avoid bugs and write more reliable code!


Want more interview preparation articles? Subscribe to EasyAdvice, bookmark the site and level up every day 💪