Using instanceof with Built-in Types
You'll learn: How to use instanceof to test if an object was created by JavaScript's built-in constructors like Array, Object, or Function.
The Core Idea
In the previous lesson, you learned that instanceof checks if a constructor's prototype appears in an object's prototype chain. JavaScript's built-in types (arrays, functions, dates, etc.) are created using constructor functions too, so you can use instanceof to identify what kind of value you're working with.
Common Built-in Types to Test
Here's how instanceof works with JavaScript's built-in constructors:
const arr = [1, 2, 3];
console.log(arr instanceof Array); // true
console.log(arr instanceof Object); // true (arrays inherit from Object)
const obj = { name: 'Alice' };
console.log(obj instanceof Object); // true
console.log(obj instanceof Array); // false
function greet() {}
console.log(greet instanceof Function); // true
console.log(greet instanceof Object); // true (functions inherit from Object)
const date = new Date();
console.log(date instanceof Date); // true
console.log(date instanceof Object); // true
Why Arrays and Functions Are Also Objects
Everything in JavaScript (except primitives) descends from Object.prototype, so nearly everything will return true for instanceof Object. This reflects the prototype chain—Array.prototype's prototype is Object.prototype, and so on.
Watch Out for Primitives
instanceof only works with objects. Primitive values always return false:
console.log('hello' instanceof String); // false (primitive string)
console.log(42 instanceof Number); // false (primitive number)
Key Takeaway: Use instanceof with built-in constructors like Array, Function, or Date to identify object types, remembering that most objects also pass the instanceof Object test due to prototype chain inheritance.