JavaScript instanceof vs typeof | difference

  • by

The main difference between JavaScript instanceof and typeof operator is tests whether the prototype property or type of primitive values.

The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.

class Foo {};
let foo = new Foo();
console.log(foo instanceof Foo);

The typeof the operator is used for getting the type of primitive values mainly. The typeof operator tests whether value belong to one of six basic types: “number“, “string“, “boolean“, “object“, “function” or “undefined“.

console.log(typeof 1);

Example instanceof vs typeof in JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
   function Bar (){};
   let bar = new Bar();
   console.log("instance of", bar instanceof Bar);

   let n = 1;
   let s = '1';
   console.log("typeof" ,typeof (n + s));
 </script>

</body>
</html> 

Output:

JavaScript instanceof vs typeof

Use instanceof for custom types:

var ClassFirst = function () {};
var ClassSecond = function () {};
var instance = new ClassFirst();
typeof instance; // object
typeof instance == 'ClassFirst'; // false
instance instanceof Object; // true
instance instanceof ClassFirst; // true
instance instanceof ClassSecond; // false 

Use typeof for simple built-in types:

'example string' instanceof String; // false
typeof 'example string' == 'string'; // true

'example string' instanceof Object; // false
typeof 'example string' == 'object'; // false

true instanceof Boolean; // false
typeof true == 'boolean'; // true

99.99 instanceof Number; // false
typeof 99.99 == 'number'; // true

function() {} instanceof Function; // true
typeof function() {} == 'function'; // true

Use instanceof for complex built-in types:

/regularexpression/ instanceof RegExp; // true
typeof /regularexpression/; // object

[] instanceof Array; // true
typeof []; //object

{} instanceof Object; // true
typeof {}; // object

And the last one is a little bit tricky:

typeof null; // object

Do comment if you have any doubts or suggestions on this Js difference topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.