[Solved] difference between typeof “andrei” and typeof “andrei”.valueOf()


No, there’s no difference, unless someone’s done something silly to the JavaScript environment.

"andrei" is a string primitive, thus typeof "andrei" is "string". If you do "andrei".valueOf(), you’re coercing a string primitive into a String object (in theory*) because you’re accessing a property on it (valueOf), and then asking that object for its primitive value — which is a primitive string, thus typeof "andrei".valueOf() is "string".

Of course, you could replace String.prototype.valueOf with something other than the default which broke tne String.prototype.valueOf contract by returning, say, a number or object. But that’s out in bizarre-land.


* “in theory” – JavaScript engines are free to optimize operations provided the optimization doesn’t make things behave in a way that isn’t according to spec. So a JavaScript engine could optimize away calling .valueOf() on a string primitive provided String.prototype.valueOf is still the same as its default value (which the engine can easily be aware of), since the result is just the same as the primitive. I don’t know whether they do, but they could.


Re your comment on the question:

 if((typeof name !="undefined") && (typeof name.valueOf()=="string") && (name.length>0))

in this one i deleted valueOf() and the result was the same and i was courious about that.

Ah! That’s a different thing, for two reasons:

  1. name may not be a string. Lots of things have length properties — strings, functions, basic arrays, typed arrays, DOM collections, any number of script-defined objects…

  2. name may be a String object (although it’s unlikely, people don’t normally use String objects unless writing extension methods for String.prototype, in which case this refers to a String object).

So removing that typeof name.valueOf()=="string" part would change the condition. Re the .valueOf() part: The author of that code is either a bit paranoid or there’s a reason to expect that name may be a String object (and so its type would be "object", not "string"). Using valueOf ensures that he/she is checking the primitive instead.

Surprisingly, they weren’t paranoid enough (at least, without context), since null would cause an exception in that code.

The () around each condition are also completely unnecessary.

Handling null as well looks like this:

if (name != null && typeof name.valueOf() == "string" && name.length > 0)

5

solved difference between typeof “andrei” and typeof “andrei”.valueOf()