JAVASCRIPT

What is the difference between typeof and instanceof?

typeof and instanceof

The difference between typeof and instanceof in JavaScript is subtle but very important. Let’s break it down clearly:


1. typeof

  • Purpose: Checks the data type of a variable or value.
  • Returns: A string indicating the type.
  • Syntax: typeof value
  • Common returned values: "undefined", "boolean", "number", "string", "bigint", "symbol", "function", "object"
    • Example:
typeof 42; // "number" 
typeof "hello"; // "string" 
typeof true; // "boolean" 
typeof {}; // "object" 
typeof null; // "object" (quirky behavior) 
typeof undefined; // "undefined" 
typeof function(){}; // "function"
  • Notes:
    • Works on primitives.
    • Cannot tell object types apart (e.g., array vs object).

2. instanceof

  • Purpose: Checks if an object is an instance of a constructor or class.
  • Returns: A boolean (true or false).
  • Syntax: object instanceof Constructor
  • Example:
const arr = [1, 2, 3]; 
arr instanceof Array; // true 
arr instanceof Object; // true 
arr instanceof String; // false 
const date = new Date(); 
date instanceof Date; // true 
date instanceof Object; // true
  • Notes:
    • Works only on objects, not primitives.
    • Checks prototype chain.
    • Useful to distinguish between object types like Array, Date, Map, etc.

Quick Comparison Table

Featuretypeofinstanceof
Checks forData type (primitive)Object type (constructor/class)
ReturnsStringBoolean
Works onPrimitives & objectsObjects only
Exampletypeof 123 // "number"[1,2] instanceof Array // true

Rule of thumb:

  • Use typeof for primitives (number, string, boolean, etc.)
  • Use instanceof for objects to check their class or constructor.
No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *