Details on the difference between the instanceof and typeof operators

  • 2020-03-30 01:16:23
  • OfStack

I. instanceof operator:
This operator determines whether a variable is an instance of an object (class) and returns a Boolean value.
To understand what it does, you must have an understanding of object orientation:

The code example is as follows:


var str=new String("antzone");  
console.log(str instanceof String);

The code above prints true because STR is an object instance of an object String.
In general, only objects created with constructors return true, otherwise false, but arrays are an exception and always return true.


Typeof operator:
This operator can return a string specifying the type of primitive arithmetic, with the following possible values:


number,boolean,string,function,object,undefined

Let's look at an example of the code:


var str=new String("antzone"); 
var strTwo="antzone";  
console.log(typeof str); 
console.log(typeof strTwo);

In the above code, the first can output the exact type "string", the second is "object", is not accurate.
Typeof generally returns the exact result if the operation is in direct form, or "object" if the object is created using the constructor, except for arrays, which return "object" regardless of whether the object is direct or not.


Related articles: