Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between typeof and instanceof in JavaScript [duplicate]

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?

like image 955
Eric Avatar asked Feb 12 '13 18:02

Eric


People also ask

What is the difference between typeof and Instanceof in JavaScript?

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.

What is Instanceof in JS?

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.

Is typeof slow JS?

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.

What is typeof in JS?

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.


1 Answers

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".

like image 80
Niet the Dark Absol Avatar answered Sep 20 '22 13:09

Niet the Dark Absol