instanceof operator –
instanceof operator is used to checking the type of an object at runtime. The instanceof operator returns a boolean value which indicates if an object is an instance of a particular class.
It’s syntax looks like –
object instanceof constructor
instanceof operator is also looking for prototype property of constructor appear anywhere in a prototype chain of the object.
First, we create a variable array using let keyword and assign an array to it. Which contain 2 elements.
let array = [“JS”, “Startup”];
Now, in the next step create another variable website and store a string in it.
let website = “jsstartup.com”;
Now, we check the instanceof array variable against Array and it give us a true.
console.log(array instanceof Array); // true
Finally, the question arises that what should be the output of the other two console log below.
console.log(website instanceof String); // ?
console.log(array instanceof Object); // ?
Now, you the answer is false, true but why this is answer. Let me explain
So First, we check the instanceof website variable which is a string but still gives a false. Because we assign String literal to website variable. As string literal is not an object.
Now, why array variable give true against object also because it’s an array and instanceof Array is also true.
Note: As you know typeof array is also an object.
So, you are checking array constructor and it is a function to create arrays. And Array is also an instanceof function.
Array instanceof Function
And function is also an objects. That’s why it gives us true
You can check this stackoverflow answer – click here.
Finaaly, That’s why we get an answer “false, true“.
I hope you understand the concept and logic behind it.
But wait, i have something more for you –
- JS Quiz – Did really the reference pass using Array.from() method
- JS Quiz – Is the String() and toString() are really same
And last but not the least, don’t forget to like, comment and share. It gives us a morale boost to remain to continue. Also, join our Facebook Page
If you have any questions, please feel free to ask me in the comment section and also let me know if you have any suggestions. As suggestions are always welcome.