Before we go into the details of difference between typeof and instanceof, let me briefly explain what is typeof.
Typeof is a operator that tells you what is the type of a given value. It always returns the type of that value in a string.
typeof 17 // "number" typeof "javascript" // "string" typeof {}; // "object" typeof []; // "object"
Difference between typeof and instanceof
There are many different ways to create(or declare) an object in javascript. Here we will use literal notation i.e we will create object with properties separated by comma inside a opening and closing curly braces.
function Farm(name, type){ this.name = name; this.type = type; } var farm1 = new Farm("Jon", "Piggery"); var farm2 = { name: "Susan", type: "Poultry" }
Here we have a constructor function Farm and we created a farm1 object with name “Jon” and type “Piggery”.
We also created farm2 object using object literal with name “Susan” and type “Poultry”.
These both objects have same properties.
And if we check the typeof both variables we get object.
typeof farm1 // "object" typeof farm2 // "object"
Here if we needed to determine which object was created by Farm constructor, typeof operator will not be helpful. As explained before typeof operator only returns the type of value. It will not be able to differentiate between objects.
In such case, we need to use instanceof operator. If the object is created with particular constructor function it will return true otherwise it will return false.
farm1 instanceof Farm // true farm2 instanceof Farm // false
Summary
1) Values returned by typeof operator are strings.
Values returned by instanceof operator are boolean.
2) typeof operator is mainly used for primitive values
instanceof operator is used for objects.