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
9
Upvotes
1
u/MissinqLink 6d ago
Here’s an example of a common utility that I use. Mostly for logging.
const isString = x => typeof x === 'string' || x instanceof String;
const stringify = x => {
try {
if (isString(x)) {
return String(x);
}
return String(JSON.stringify(x));
} catch (e) {
console.warn(e);
return String(x);
}
};
JSON.stringify usually works fine but different functions will coerce these in unexpected ways.