Sub topic 15
String Primitives Versus String Objects
This chapter assumes you know basic JavaScript syntax, can run code in Node.js or a browser console, and have read the earlier chapters on string literals and converting values to strings. It explains why "x" and new String("x") behave differently, why methods work on primitives anyway, and how to check for strings and convert values to strings without running into the wrapper type.
Two Kinds of String Value
JavaScript has a primitive string type and a String object type. A string primitive is an immutable value with no identity of its own. The literals "x", 'x', and ` x all produce primitives, and so does calling String(value) without new. A **String object**, also called a wrapper object, is a normal object with an internal slot that holds a primitive string. You get one by calling new String(value) or Object("x")`.
const prim = "x";
const obj = new String("x");
console.log(typeof prim); // string
console.log(typeof obj); // object
console.log(prim === obj); // false
console.log(prim == obj); // true
console.log(String(null), String(42), `${[1, 2]}`); // null 42 1,2Strict equality (===) fails because the two values have different types. Loose equality (==) succeeds because when one side is an object and the other is a primitive, the engine converts the object to a primitive first. That conversion calls obj.valueOf(), which returns "x", so the comparison becomes "x" == "x".
| Expression | Primitive `"x"` | Object `new String("x")` |
|---|---|---|
| `typeof v` | `"string"` | `"object"` |
| `v instanceof String` | `false` | `true` |
| `v === "x"` | `true` | `false` |
| Truthy when empty (`""`) | No | Yes |
| Can hold custom properties | No | Yes |
| Compared by | Value | Identity (reference) |
How Methods Work on Primitives
Primitives have no properties, yet "hello".toUpperCase() works. When you read a property from a primitive, the language specification says the engine converts it with an operation called ToObject. Conceptually this creates a temporary String wrapper, looks the property up through String.prototype, calls the method, and throws the wrapper away. Modern engines skip the allocation and go straight to String.prototype, but the observable behavior matches the specification.
Because each wrapper is temporary, writing a property to a primitive does not stick:
// Sloppy mode (no "use strict")
const s = "hello";
s.tag = "greeting"; // written to a throwaway wrapper
console.log(s.tag); // undefinedIn strict mode, which ES modules and class bodies always use, the same assignment throws:
"use strict";
const s = "hello";
try {
s.tag = "greeting";
} catch (e) {
console.log(e instanceof TypeError); // true
console.log(e.message); // Cannot create property 'tag' on string 'hello' (V8 wording)
}The value of `this` in methods you add
If you add a method to String.prototype, which you should avoid in shared code, the value of this depends on the mode. In strict mode, this is the primitive. In sloppy mode, this is the wrapper object.
String.prototype.kindStrict = function () {
"use strict";
return typeof this;
};
String.prototype.kindSloppy = function () {
return typeof this;
};
console.log("a".kindStrict()); // string
console.log("a".kindSloppy()); // object
delete String.prototype.kindStrict;
delete String.prototype.kindSloppy;This matters when such a method compares this === "a". The comparison is false in sloppy mode.
Gotchas With String Objects
Every wrapper is truthy
All objects are truthy, including a wrapper around the empty string. Code that relies on if (str) to reject empty input breaks if it receives a wrapper.
const empty = new String("");
console.log(empty.length); // 0
console.log(Boolean(empty)); // true
if (empty) console.log("runs even though the text is empty");Objects compare by identity
Two wrappers that hold the same text are different objects. Neither == nor === converts them, because both sides are objects.
const a = new String("id");
const b = new String("id");
console.log(a == b); // false
console.log(a.valueOf() === b.valueOf()); // trueThe same rule affects switch, which uses strict equality, and collections that key on identity:
function label(v) {
switch (v) {
case "id": return "matched";
default: return "no match";
}
}
console.log(label("id")); // matched
console.log(label(new String("id"))); // no match
const set = new Set([new String("a"), new String("a")]);
console.log(set.size); // 2
console.log(new Set(["a", "a"]).size); // 1Wrappers expose index keys
A String object has own properties for each index and a non-enumerable length. A primitive has no own properties. Object.keys accepts both, because it converts its argument to an object first.
console.log(Object.keys(new String("ab"))); // [ '0', '1' ]
console.log(Object.keys("ab")); // [ '0', '1' ]
console.log(JSON.stringify(new String("ab"))); // "ab"
console.log(JSON.stringify({ v: new String("ab") })); // {"v":"ab"}JSON.stringify unwraps String objects, so serialized output looks the same for both kinds. The difference shows up only at runtime.
Checking Whether a Value Is a String
For almost all code, check for the primitive only:
function isString(v) {
return typeof v === "string";
}If you must also accept wrappers, for example in a library that receives arbitrary input, instanceof String is one option, but it fails for objects created in another realm such as an iframe or a Node.js vm context. Each realm has its own String constructor. The tag check from Object.prototype.toString works across realms:
function isStringLike(v) {
return typeof v === "string" ||
Object.prototype.toString.call(v) === "[object String]";
}
console.log(isStringLike("x")); // true
console.log(isStringLike(new String("x"))); // true
console.log(isStringLike(["x"])); // falseAn object with a custom Symbol.toStringTag property can fake this tag, so treat the check as a strong hint rather than a guarantee. To get a primitive back from a value that passes, call String(v) or v.valueOf().
Converting Values to Strings Safely
The earlier chapter on conversion covered the basic rules. Two details connect directly to wrapper objects and object-to-primitive conversion.
Conversion order differs between `String()` and `+ ""`
String(v) and template literals ask the object for a primitive with a "string" hint, which tries toString before valueOf. Concatenation with + uses a "default" hint, which tries valueOf first for ordinary objects.
const obj = {
toString() { return "T"; },
valueOf() { return 42; },
};
console.log(String(obj)); // T
console.log(`${obj}`); // T
console.log(obj + ""); // 42Date objects are an exception: they treat the default hint as "string", so new Date(0) + "" gives the readable date text.
Symbols, null, and undefined
String() is the only common conversion that handles every type. Calling .toString() throws on null and undefined, and implicit conversion throws on symbols.
const sym = Symbol("k");
console.log(String(sym)); // Symbol(k)
console.log(String(undefined)); // undefined
try { `${sym}`; } catch (e) { console.log(e.name); } // TypeError
try { sym + ""; } catch (e) { console.log(e.name); } // TypeError
try { null.toString(); } catch (e) { console.log(e.name); } // TypeError| Technique | `null` | Symbol | Object with both methods | Result type |
|---|---|---|---|---|
| `String(v)` | `"null"` | `"Symbol(k)"` | uses `toString` | primitive |
| `` `${v}` `` | `"null"` | throws | uses `toString` | primitive |
| `v + ""` | `"null"` | throws | uses `valueOf` | primitive |
| `v.toString()` | throws | `"Symbol(k)"` | uses `toString` | whatever it returns |
| `new String(v)` | wrapper of `"null"` | `"Symbol(k)"` wrapped | uses `toString` | object |
When You Might Meet Wrappers
You rarely create wrappers on purpose, but they still turn up. Older code may use new String by mistake. Object(value) returns a wrapper for a primitive string. Sloppy-mode prototype methods receive this as a wrapper. Some serialization or proxy layers box values. In each case, unwrap at the boundary with String(v) or v.valueOf(), and keep primitives everywhere else.
Exercise
What does this code log, and why? const a = new String("ok"); const b = "ok"; console.log(a == b, a === b, typeof a, Boolean(new String("")));
Show answer
It logs true false object true. a == b converts the object to its primitive "ok", so it is true. a === b compares an object with a primitive, so it is false. typeof a is "object" because new String creates a wrapper. Boolean(new String("")) is true because every object is truthy, even a wrapper around an empty string.
Exercise
In strict mode, what happens when you run const s = "hi"; s.count = 1;? What happens in sloppy mode, and what is s.count afterward?
Show answer
In strict mode, the assignment throws a TypeError because you cannot create a property on a primitive. In sloppy mode, the property is written to a temporary wrapper that is thrown away immediately, so no error occurs and s.count is undefined.
Exercise
Given const v = { toString() { return "A"; }, valueOf() { return "B"; } };, what do String(v), ` ${v} , and v + ""` produce?
Show answer
String(v) and the template literal both produce "A", because they request a string-hinted primitive and try toString first. v + "" produces "B", because + uses the default hint, which tries valueOf first for ordinary objects.
Exercise
Write a function toPlainString(v) that returns a primitive string for primitive strings and String objects (including ones from other realms) and returns null for anything else.
Show answer
function toPlainString(v) { if (typeof v === "string") return v; if (Object.prototype.toString.call(v) === "[object String]") return String.prototype.valueOf.call(v); return null; } Calling String.prototype.valueOf directly throws if the value is not a real String object (for example, one that fakes the tag with Symbol.toStringTag), so you can wrap it in try/catch and return null if you need to reject such objects.