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?
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;
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