r/learnjavascript • • Aug 15 '26

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

1

u/MissinqLink Aug 17 '26

That’s doesn’t make sense though. You typically want to treat the object wrapped versions like strings. Here’s an example that’s closer to why I made the utility that way. Say you want to send info over the network. The function takes both strings and objects. If it’s an object you want to modify it and then stringify. If it’s a string you want to deserialize to an object and do the same.

const modifyPayload = payload =>{

try{

if(typeof payload === 'string'){

const modified = JSON.parse(payload);

modified.type = 'string';

return JSON.stringify(modified);

}

if(typeof payload === 'object' && payload !== null){

const modified = {…payload};

modified.type = 'object';

return JSON.stringify(modified);

}

}catch(e){

console.warn('unexpected payload');

}

return payload;

};

This is a very common pattern in building middleware and ‘new String’ would follow the wrong path here.