Sub topic 15
String Primitives Versus String Objects
This chapter assumes you know basic JavaScript syntax, typeof, and the difference between == and ===. It explains why "x" and new String("x") behave differently, and why you should almost always use the first.
Two Kinds of String Value
JavaScript has two ways to hold text:
- A string primitive is a plain, immutable value such as
"x".typeofreports"string". - A String object is a wrapper object created with
new String("x").typeofreports"object".
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,2=== returns false because the two values have different types. == returns true because loose equality converts the object to a primitive by calling its valueOf method, and then compares the two primitives.
How Primitives Get Methods
A primitive has no properties of its own. So how does "hello".toUpperCase() work? When you access a property on a primitive, the engine briefly wraps it in a String object, looks the property up on String.prototype, and throws the wrapper away. This is called autoboxing.
Each property access creates a new wrapper, so anything you attach to that wrapper is lost:
const s = "abc";
s.note = "hi"; // sloppy mode: assigned to a temporary wrapper
console.log(s.note); // undefinedIn strict mode, the assignment throws TypeError: Cannot create property 'note' on string 'abc'.
Common Errors with String Objects
| Behavior | Primitive `"..."` | `new String("...")` |
|---|---|---|
| `typeof` | `"string"` | `"object"` |
| `Boolean("")` vs empty object | `""` is falsy | `new String("")` is truthy |
| Two equal values with `===` | `true` | `false` (different objects) |
| Two equal values with `==` | `true` | `false` (compares references) |
| Can hold custom properties | No | Yes |
const empty = new String("");
if (empty) console.log("runs: objects are always truthy");
const a = new String("hi");
const b = new String("hi");
console.log(a == b, a === b); // false false
console.log(a.valueOf() === b.valueOf()); // trueThese mistakes usually come from code that writes new String(value) when it meant to convert a value to text.
Getting the Primitive Back
If a String object reaches your code, for example from an old library, call valueOf() or String(obj) to unwrap it. To accept both forms in a type check, test for either:
function isString(v) {
return typeof v === "string" || v instanceof String;
}
console.log(isString("x"), isString(new String("x")), isString(1)); // true true falseExercise
What does this print, and why? const t = new String("0"); console.log(t ? "yes" : "no", t == "0", t === "0");
Show answer
It prints yes true false. t is an object, and all objects are truthy. == unwraps t to the primitive "0" with valueOf, so the comparison is true. === compares an object with a primitive, so it is false.
Exercise
A function receives new String("ok") and checks typeof input === "string". The check fails. Give two fixes.
Show answer
Convert the input first with String(input) or input.valueOf() and then check it, or widen the check to typeof input === "string" || input instanceof String.