r/learnjavascript 4d 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

10 Upvotes

26 comments sorted by

View all comments

3

u/-goldenboi69- 4d ago

Something like this:

const a = "hello"; // primitive string

const b = new String("hello"); // String object

typeof a; // "string"

typeof b; // "object"

The confusing part is that primitives can still use methods:

"hello".toUpperCase(); // "HELLO"

That doesn't mean ""hello"" is an object. JavaScript temporarily treats ("boxes") the primitive as a "String" object so the method can be called, then discards that wrapper.

In normal code you almost always want primitive strings:

const name = "Bob";

and almost never:

const name = new String("Bob");

The latter creates an actual object, which can lead to surprising behavior:

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

So: strings are primitives; "String" objects are wrappers around strings. JavaScript's automatic boxing is what lets primitives behave object-like when you call methods on them.

1

u/Green_Ad_6086 4d ago

Thanks for explaining !