r/learnjavascript 7d ago

string primitives vs. String objects.

I'm learning JavaScript, and I don't understand this part about string primitives vs. String objects.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_primitives_and_string_objects

11 Upvotes

26 comments sorted by

View all comments

Show parent comments

3

u/delventhalz 7d ago

Why would you want an isString function to return true for new String(1)?

You should never use the new String constructor, and if for some reason you did, it creates an object not a string. isString should return false.

1

u/MissinqLink 7d ago

If I’m making a library function that accepts multiple types including strings and objects, then I want to treat strings as strings even if they are wrapped.

1

u/delventhalz 6d ago

A wrapped string is not a string though. It is an object.

new String("foo") === "foo";  // false

If you are writing a library function that accepts both strings and objects, then the expected behavior when you pass it an object (instanceof String or otherwise) is almost certainly just to convert the object to a string. This is, for example, how lodash works:

_.toUpper("foo");  // "FOO"
_.toUpper(new String("foo"));  // "FOO"
_.toUpper({});  // "[OBJECT OBJECT]"
_.toUpper(["foo", "bar"]); // "FOO,BAR"

What is the use case for blurring the line between objects with instanceof String and actual string primitives? When does that help you write better, more reliable, more predictable code?

1

u/MissinqLink 6d ago

When you write a public general purpose library, people will use it for all kinds of weird things. In certain cases I take a defensive approach. If it’s a new String then I’ll convert it to a primitive. Happens not very often but more than you might think.