Sub topic 7
How Primitives Get Methods: Wrapper Objects
This chapter assumes you know the seven primitive types, how object references behave, and what typeof returns. Those topics were covered earlier. Here we answer a question those chapters left open: if a primitive is not an object, how can "hello".toUpperCase() work?
The Puzzle
A primitive is a plain value with no properties of its own. Yet this runs without error:
const greeting = "hello";
console.log(greeting.length); // 5
console.log(greeting.toUpperCase()); // "HELLO"
console.log((3.14159).toFixed(2)); // "3.14"
console.log(true.toString()); // "true"The methods are not stored on the string. They live on String.prototype, Number.prototype, and Boolean.prototype. To reach them, JavaScript briefly converts the primitive into an object. That temporary object is called a wrapper object, and the automatic conversion is called autoboxing.
How Autoboxing Works
When you read a property from a primitive, the engine performs the abstract operation ToObject on it. ToObject creates a wrapper whose internal slot holds the primitive value. The property lookup then runs on that wrapper and follows its prototype chain in the usual way.
| Primitive type | Wrapper constructor | Prototype that supplies methods |
|---|---|---|
| string | `String` | `String.prototype` |
| number | `Number` | `Number.prototype` |
| boolean | `Boolean` | `Boolean.prototype` |
| symbol | `Symbol` | `Symbol.prototype` |
| bigint | `BigInt` | `BigInt.prototype` |
| undefined | none | none |
| null | none | none |
The specification describes the wrapper conceptually. Modern engines optimize it away and look the method up directly on the prototype, so autoboxing costs nothing measurable in practice. What you can observe is the behavior, and the behavior matches the model above.
null and undefined Have No Wrappers
ToObject throws for null and undefined, because they have no wrapper type. This is the source of one of the most common runtime errors:
const user = { name: null };
try {
user.name.toUpperCase();
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message); // e.g. "Cannot read properties of null (reading 'toUpperCase')"
}The exact message varies by engine, but the error type is always TypeError.
Writes to Primitives Disappear
Because the wrapper is temporary, any property you assign to it is thrown away with it. In sloppy (non-strict) mode the write fails silently. In strict mode it throws.
function sloppyWrite() {
const s = "abc";
s.tag = "important"; // assigned to a throwaway wrapper
return s.tag; // a new wrapper is created, with no tag
}
function strictWrite() {
"use strict";
const s = "abc";
try {
s.tag = "important";
} catch (err) {
return err.constructor.name;
}
}
console.log(sloppyWrite()); // undefined
console.log(strictWrite()); // "TypeError"ES modules and class bodies are always strict, so in modern code you will usually see the TypeError.
Calling the Constructors: With and Without new
The wrapper constructors behave very differently depending on whether you use new.
- Called without
new,String(x),Number(x), andBoolean(x)are explicit conversion functions. They return primitives. Later chapters use them heavily. - Called with
new, they create a wrapper object that persists.
const prim = String("hi");
const boxed = new String("hi");
console.log(typeof prim); // "string"
console.log(typeof boxed); // "object"
console.log(boxed instanceof String); // true
console.log(prim instanceof String); // falseSymbol and BigInt refuse new entirely, so you can't create those wrappers by accident:
try { new Symbol("id"); } catch (e) { console.log(e.constructor.name); } // "TypeError"
try { new BigInt(5); } catch (e) { console.log(e.constructor.name); } // "TypeError"
// Object() can still box them if you really want a wrapper:
const boxedSym = Object(Symbol("id"));
console.log(typeof boxedSym); // "object"Gotchas of Explicit Wrappers
Wrapper objects are objects. They follow object rules for truthiness, equality, and identity, and those rules often contradict what the wrapped value suggests.
A false Boolean that is truthy
Every object is truthy, including a wrapper around false:
const flag = new Boolean(false);
if (flag) {
console.log("runs!"); // this line executes
}
console.log(flag.valueOf()); // falseEquality compares identity
Two wrappers around the same value are different objects. Strict equality between a wrapper and a primitive is always false, because their types differ. Loose equality unwraps the object first, so it returns true.
const a = new String("x");
const b = new String("x");
console.log(a === b); // false: two distinct objects
console.log(a == b); // false: both are objects, so == compares identity
console.log(a === "x"); // false: object vs string
console.log(a == "x"); // true: the wrapper is converted to "x"
console.log(a.valueOf() === "x"); // trueThey behave strangely as keys and in collections
const set = new Set([new Number(1), new Number(1), 1]);
console.log(set.size); // 3: two distinct objects plus one primitiveUnwrapping
Every wrapper's valueOf() returns the primitive it holds. Arithmetic and template literals unwrap automatically, through the object-to-primitive process covered in a later chapter.
const n = new Number(41);
console.log(n + 1); // 42
console.log(typeof (n + 1)); // "number"
console.log(`${new String("ok")}`); // "ok"What `this` Is Inside a Prototype Method
When a method from a wrapper's prototype runs, what is this? In strict mode functions, this is the original primitive. In sloppy mode functions, this is boxed into a wrapper object. The demo below adds a method temporarily, then removes it. Don't extend built-in prototypes in real code.
String.prototype.strictThis = function () {
"use strict";
return typeof this;
};
String.prototype.sloppyThis = function () {
return typeof this;
};
console.log("abc".strictThis()); // "string"
console.log("abc".sloppyThis()); // "object"
delete String.prototype.strictThis;
delete String.prototype.sloppyThis;This difference matters when you compare this with === inside a sloppy-mode function. A comparison like this === "abc" returns false because this is a wrapper.
Practical Guidance
| Situation | Recommendation |
|---|---|
| Converting a value to a primitive | Use `String(x)`, `Number(x)`, `Boolean(x)` without `new` |
| Creating strings, numbers, booleans | Use literals: `"a"`, `1`, `true` |
| Seeing `typeof x === "object"` for something that looks like a string | Suspect a wrapper and call `x.valueOf()` |
| Linting | Enable ESLint's `no-new-wrappers` rule |
Exercise
What does this code log, and why? const s = "cat"; s.color = "black"; console.log(s.color, s.length); (Assume sloppy mode.)
Show answer
It logs undefined 3. The assignment goes to a temporary String wrapper that is discarded immediately. Reading s.color creates a fresh wrapper with no color property. length comes from the wrapper's internal string value, so it is 3.
Exercise
A function receives value = new Boolean(false). Predict the results of !!value, value == false, and value === false, and explain each.
Show answer
!!value is true because every object is truthy. value == false is true because loose equality converts the wrapper to a primitive (false, then 0) and compares it with false (0). value === false is false because an object and a boolean are different types.
Exercise
Why does "abc".missing.toUpperCase() throw a TypeError when "abc".toUpperCase() works?
Show answer
"abc".missing autoboxes the string, finds no missing property, and returns undefined. Calling .toUpperCase() on undefined requires ToObject, which throws because undefined has no wrapper type.