muriithi
muriithi

Reputation: 131

Why does Javascript's instanceof return true for these native constructors?

This is on Mozilla Firefox web console;

> Function instanceof Function;
>true

>Array instanceof Function;
>true

>String instanceof Function
>true

Upvotes: 0

Views: 59

Answers (2)

Sampson
Sampson

Reputation: 268424

Typically people don't use the constructors for these types, opting instead for literals like [], "", and function(){}. However, you can create strings, arrays, and functions using their constructor methods:

var str = new String("Hello World");

Note that we're calling a function - the string constructor. The same is the case with arrays:

var arr = new Array("Hello", "World");

Again, calling a function. These are all instances of Function because we used their constructor. This isn't the case with literals:

var str = "Hello World";
console.log( str instanceof Function ); // false

var arr = ["Hello", "World"];
console.log( arr instanceof Function ); // false

Upvotes: 1

hvgotcodes
hvgotcodes

Reputation: 120268

Because all constructors are functions, and Function, Array, and String are all constructors (i.e., you use new with them).

Upvotes: 6

Related Questions