Skip to content

What is the difference between typeof and instanceof?

  • by

Use Use instanceof for custom types and use typeof for simple and complex built-in types, this is the main difference between typeof and instanceof in JavaScript.

The typeof is a unary operator that returns a string indicating the type of the unevaluated operand.

Where instanceof is a binary operator, that accepts an object and a constructor. It returns a boolean indicating whether or not the object has the given constructor in its prototype chain.

JavaScript instanceof vs typeof Example

Simple example code where type checking of given values in JavaScript

<!DOCTYPE html>
<html>
<body>
  <script>
    const a = "String Primitive";
    const b = new String("String Object");

    console.log(typeof(a))
    console.log(typeof(b))

    console.log(a instanceof String)
    console.log(b instanceof Object)

  </script>
</body>
</html> 

Output:

What is the difference between typeof and instanceof

When use which one?

Answer: A good reason to use typeof is if the variable may be undefined.

alert(typeof undefinedVariable); // alerts the string "undefined"
alert(undefinedVariable instanceof Object); // throws an exception

A good reason to use instanceof is if the variable may be null.

var myNullVar = null;
alert(typeof myNullVar ); // alerts the string "object"
alert(myNullVar  instanceof Object); // alerts "false"

So really in my opinion it would depend on what type of possible data you are checking.

Source: stackoverflow.com

Extra

1. If you want to check if a value is a primitive string or an String object, then you need to use both operators:

const isString = (value) => typeof value === 'string' || value instanceof String;
isString('helloworld'); // trueisString(new String('helloworld')); // true

2. There is a special case when using typeof with null:

typeof null; // 'object', not 'null'

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading