How do strings get methods?
You noticed that a primitive string has methods (toUpperCase), even though it's not an object. This is JavaScript " magic " called primitive wrappers.
1. The Wrapper Mechanism
When you access a primitive's property, the JS engine:
- Creates a temporary wrapper object (e.g.,
new String). - Calls the method on this object.
- Immediately destroys the wrapper object.
2. Trying to add a property
let str = "Hello";
str.test = 5; // Temporary object created, property added...
alert(str.test); // undefined (object is already deleted, this is a NEW temporary object)
Caution
Never use constructors like new Number(1) or new String("a"). This creates a fully-fledged object, which breaks type logic: typeof (new Number(1)) will return "object", not "number".
Important
The null and undefined primitives don't have wrappers. Trying to call a method on them will lead to the most common JS error: Cannot read property ... of null.