Monday, January 11, 2016

Instanceof String

I was playing with javascript error handling and understanding where to use try/catch today when I ran into an interesting problem. As part of my error handling I tried to include a type check on the key portion of a key-value pair, just to ensure that the key is actually a string and not null, undefined, numeric... 


That's when I noticed the following...


According to MDN (ctrl + f "Primitives and string objects") javascript handles string primitives differently from string objects. When creating a string with single or double quotes, or the global String object, javascript returns a primitive string. However, when creating a string with the new keyword, javascript returns a new string object. This makes sense when you read it, but if you're unaware or unfamiliar it could easily bite you. 

Finally, the documentation does say that "JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings". The problem is that Javascript only does this for String object methods, but instanceof is not a string object method. Instead, since instanceof is a global relational operator, the string created by quotes remains a primitive string and fails the instanceof String test.

No comments:

Post a Comment