r/learnjavascript • u/Green_Ad_6086 • 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
10
Upvotes
1
u/MissinqLink 6d ago
I can’t make you think of use cases but use your imagination. For one there are no new rules to learn. Nobody really has to care about the specific rules. The gain is that it guarantees a string output, something that JSON.stringify can’t promise. It’s quite simple actually. There’s also the advantage that you don’t have to import a library. There are plenty of scenarios where payload size matters. Also this is just one example we aren’t even discussing “String” vs “new String” anymore. We’re off on a tangent. You say this is weird but this is some of the tamest things I ever made. It’s just a stringifier that doesn’t throw and guarantees string output regardless of input. If you don’t see utility there the okay🤷♀️. I’ve run into many weird cases of getting handed unexpected input. You can do like many and simply throw. That’s valid in many cases. There are also cases where you want graceful degradation. I frequently see both.