I'm working with node.js, so this could be specific to V8.
I've always noticed some weirdness with differences between typeof and instanceof, but here is one that really bugs me:
var foo = 'foo'; console.log(typeof foo); Output: "string" console.log(foo instanceof String); Output: false
What's going on there?
typeof: Per the MDN docmentation, typeof is a unary operator that returns a string indicating the type of the unevaluated operand. instanceof: is a binary operator, accepting an object and a constructor. It returns a boolean indicating whether or not the object has the given constructor in its prototype chain.
The instanceof operator in JavaScript is used to check the type of an object at run time. It returns a boolean value if true then it indicates that the object is an instance of a particular class and if false then it is not.
Typeof is most definitely slower. Why? Well by analyzing what is occurring we can see that we first perform a typeof operation, then compare 1 string to another string.
typeof is a JavaScript keyword that will return the type of a variable when you call it. You can use this to validate function parameters or check if variables are defined. There are other uses as well. The typeof operator is useful because it is an easy way to check the type of a variable in your code.
typeof
is a construct that "returns" the primitive type of whatever you pass it.instanceof
tests to see if the right operand appears anywhere in the prototype chain of the left.
It is important to note that there is a huge difference between the string literal "abc"
, and the string object new String("abc")
. In the latter case, typeof
will return "object" instead of "string".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With