Examples
Using instanceof with String
The following example shows the behavior of instanceof
with String
objects.
const literalString = 'This is a literal string'; const stringObject = new String('String created with constructor'); literalString instanceof String; // false, string primitive is not a String stringObject instanceof String; // true literalString instanceof Object; // false, string primitive is not an Object stringObject instanceof Object; // true stringObject instanceof Date; // false
Using instanceof with Date
The following example shows the behavior of instanceof
with Date
objects.
const myDate = new Date(); myDate instanceof Date; // true myDate instanceof Object; // true myDate instanceof String; // false
Objects created using Object.create()
The following example shows the behavior of instanceof
with objects created using Object.create()
function Shape() { } function Rectangle() { Shape.call(this); // call super constructor. } Rectangle.prototype = Object.create(Shape.prototype); Rectangle.prototype.constructor = Rectangle; const rect = new Rectangle(); rect instanceof Object; // true rect instanceof Shape; // true rect instanceof Rectangle; // true rect instanceof String; // false const literalObject = {}; const nullObject = Object.create(null); nullObject.name = "My object"; literalObject instanceof Object; // true, every object literal has Object.prototype as prototype ({}) instanceof Object; // true, same case as above nullObject instanceof Object; // false, prototype is end of prototype chain (null)
Demonstrating that mycar
is of type Car
and type Object
The following code creates an object type Car
and an instance of that
object type, mycar
. The instanceof
operator demonstrates that
the mycar
object is of type Car
and of type
Object
.
function Car(make, model, year) { this.make = make; this.model = model; this.year = year; } const mycar = new Car('Honda', 'Accord', 1998); const a = mycar instanceof Car; // returns true const b = mycar instanceof Object; // returns true
Not an instanceof
To test if an object is not an instanceof
a specific constructor, you can
do
if (!(mycar instanceof Car)) { // Do something, like: // mycar = new Car(mycar) }
This is really different from:
if (!mycar instanceof Car) { // unreachable code }
This will always be false
. (!mycar
will be evaluated before
instanceof
, so you always try to know if a boolean is an instance of
Car
).