Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do any standard JavaScript APIs or libraries return strings as String objects?

Until recently, I didn't realise that there are two types of strings (and bools, and numbers) in JavaScript: primitives such as "blah", and objects such as new String("blah").

They differ in very "gotcha"-prone ways, the biggest one of which seems to be the different typeof value ("string" vs "object"), but a number of other differences exist, some documented at MDN.

There's no point in creating String objects because the primitive strings work just as well, and JSHint even treats this as an error. So I'd really like to pretend String instances don't even exist, and only support primitive strings in my code.

This makes me wonder: can I get a surprise String instance by calling some standard API that returns a string? Or is it really safe to assume that unless someone screws up by explicitly writing new String, I will never see one of these?

like image 262
Roman Starkov Avatar asked Jul 10 '14 13:07

Roman Starkov


1 Answers

This github search shows that some people are using new String.

And this answer has a nice explanation for String obj:

No native JavaScript object, major library or DOM method that returns a string will return a String object rather than a string value. However, if you want to be absolutely sure you have a string value rather than a String object, you can convert it as follows:

var str = new String("foo");
str = "" + str;
like image 78
ymutlu Avatar answered Sep 21 '22 09:09

ymutlu