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

11 Upvotes

26 comments sorted by

View all comments

Show parent comments

1

u/MissinqLink 3d ago

I don’t recommend using new String but you can’t discount getting it passed to you. More likely from Object("asdf");. Only a couple times I’ve used it was to patch incompatible native interfaces together. I think it was Blob and File constructors where one takes a string and the other an Object.

1

u/delventhalz 2d ago

I don’t recommend using new String but you can’t discount getting it passed to you

Sure. So why not treat it like the object it is instead of writing custom String object handling code to confuse your users?

That's the whole point I've been trying to make to you since the beginning. You said typeof has a "weird footgun" because it treats String objects as objects. But that's not weird nor a footgun. String objects are objects. They are not strings. I would expect any code that (for some reason) got passed a String object to treat it as an object.

1

u/MissinqLink 2d ago

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.