Skip to Content
Course content

15: typeof and instanceof

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I remember early in my career, I was building a data-processing pipeline for a client. I had a function that expected an array of user IDs, and to be "safe," I added a check: if (typeof ids === 'object'). It seemed logical—arrays are objects, right? Everything worked perfectly in testing. Then, the first time we hit production, the API occasionally returned null when no users were found. Because typeof null is actually 'object' in JavaScript (a legacy bug that can never be fixed without breaking the internet), my code tried to run a .forEach() on null and crashed the entire process. I spent three hours staring at a stack trace before I realized my type-checking was lying to me.

The Limits of typeof

The typeof operator is your go-to for checking primitive values. If you need to know if a variable is a string, a number, or a boolean, it's fast and reliable. I use it all the time for simple input validation. For example, if you're writing a function that formats a price, you'll want to make sure the input is actually a number before you try to call .toFixed(2) on it.

const price = 19.99;
if (typeof price === 'number') {
  console.log(price.toFixed(2));
}

But as I learned the hard way, typeof is a blunt instrument. It doesn't distinguish between different types of objects. Whether you have a plain object, an array, a Date object, or null, typeof will tell you it's an 'object'. This is where you'll find yourself reaching for something more surgical.

Precision Checking with instanceof

When you need to know exactly what kind of object you're dealing with, instanceof is the tool for the job. Instead of returning a string, instanceof returns a boolean by checking if the constructor of the object exists anywhere in the object's prototype chain. I find this incredibly useful when dealing with custom classes or built-in complex objects like Dates or Arrays.

If we go back to my payment pipeline disaster, instanceof Array would have saved me. null instanceof Array is false, whereas typeof null === 'object' is true. Here is how that distinction looks in practice:

const users = ['Alice', 'Bob'];
const emptyResponse = null;

console.log(users instanceof Array);      // true
console.log(emptyResponse instanceof Array); // false

const now = new Date();
console.log(now instanceof Date);        // true
console.log(typeof now);                 // 'object' (Not very helpful!)

One thing to keep in mind: instanceof is specifically for objects. If you try to use it on a primitive string or number, it will return false because those aren't instances of the Object constructor in the way you'd expect. I usually follow a simple rule of thumb: use typeof for primitives and instanceof for anything created with new or built-in object types.




📋 Practical Task

Build a Mixed-Type Data Filter

Imagine you are receiving a "dirty" stream of data from a legacy API. The data arrives as an array containing a mix of strings, numbers, dates, and plain objects. Your goal is to write a function called sortDataByType that organizes this mess into a categorized object.

Requirements:

  • Create a function sortDataByType(inputArray).
  • The function should return an object with four keys: strings, numbers, dates, and others.
  • Use typeof to identify strings and numbers.
  • Use instanceof to identify Date objects.
  • Anything that doesn't fit those three categories should go into others.

Test your function with this array:

const rawData = ["Hello", 42, new Date(), { id: 1 }, "World", 100, new Date(), null, [1, 2, 3]];
// Expected result: 
// { 
//   strings: ["Hello", "World"], 
//   numbers: [42, 100], 
//   dates: [Date object, Date object], 
//   others: [{ id: 1 }, null, [1, 2, 3]] 
// }
Rating
0 0

There are no comments for now.

to be the first to leave a comment.