跪拜 Guibai
← Back to the summary

Why 'hello'.a Is undefined: JS Objects, Prototypes, and Boxing Explained

Thoroughly Understanding JS Objects: Data Types, Prototype Chain, and Wrapper Classes

Learning JS to a certain level, almost everyone hits the same wall: object-related knowledge seems understandable—literals are written, properties are accessed, new is used—but as soon as a problem turns a corner, confidence wavers.

For example, 'hello'.length is obviously 5, but adding a property to 'hello' doesn't work; two objects that look identical are false when compared with ===; instances created with new can call methods that the constructor never wrote.

These are not isolated knowledge points, but projections of the same set of rules from different angles: how values are stored, how properties are found, how primitive types "pretend" to be objects.

This article follows that line: first completely separate basic types and reference types, then break down the four steps of new, then draw the prototype chain, and finally return to the seemingly most unreasonable phenomenon of 'hello'.a—you'll find it's just the inevitable result of "boxing, reading, discarding".

All the code in the article can run directly, and the output is the real result. The standard for finishing is simple: given a piece of code involving objects, you can say why it produces this result before running it.

Three seemingly contradictory phenomena

console.log('hello'.length)   // 5
'hello'.a = 2                 // no error
console.log('hello'.a)        // undefined

You can read length, meaning strings are "like" objects; if they're like objects, why can't you add a property to them?

Then two more common ones:

const a = { n: 1 }
const b = a
b.n = 2
console.log(a.n)        // 2  — obviously we changed b

console.log({ n: 1 } === { n: 1 })   // false — looks identical but isn't equal

These three questions point to the same underlying rules: what "objects" are in JS, how values are stored, how properties are found. Once these three things are clear, there is no black box in the object world.


1. First distinguish: basic types and reference types

JS data types are divided into two categories.

Basic types (7 kinds)

Type Example
number 1, 3.14, NaN
string 'hello'
boolean true / false
null null
undefined undefined
symbol Symbol('a')
bigint 10n

Reference types

object is the only reference type. But arrays, functions, dates, regular expressions, errors—all are essentially objects:

console.log(typeof 1)              // number
console.log(typeof 'a')            // string
console.log(typeof null)           // object   ← historical bug
console.log(typeof [])             // object
console.log(typeof function () {}) // function ← functions are objects too, but typeof has a special case

Also a common interview question: typeof null returns "object", which is a bug in the first version of JS, kept for compatibility. To judge null, use x === null.

Look at symbol again. Its most common use is creating "never-equal" identifiers:

console.log(Symbol('a') === Symbol('a'))  // false
console.log('hello' === 'hello')          // true

Even if the description is the same, two Symbol() calls produce different values. That's why it's suitable as a "hidden key" in objects.


2. Is "everything is an object" correct?

Only half right.

But when you write 'hello'.length, the code does run correctly. This isn't a contradiction; the engine does a temporary conversion behind the scenes—that's the "wrapper class" in section 7. Remember the conclusion first: basic types are not objects, they just "borrow" the object's methods.


3. Value vs. reference: the easiest pitfall

const a = { n: 1 }
const b = a
b.n = 2
console.log(a.n)   // 2

const b = a doesn't copy a new object; it copies the address of the same object to b. So changing b.n is changing a.n.

Compare basic types:

let a = 1
let b = a
b = 2
console.log(a)     // 1

Basic types copy the value itself; changing b doesn't affect a.

Another phenomenon beginners often find confusing:

console.log({ n: 1 } === { n: 1 })   // false

=== compares objects by reference (address), not content. The two literals create two different objects with different addresses, so they aren't equal. To compare content, you must compare key by key (or use JSON.stringify, but it has pitfalls, discussed later).


4. Creating objects and CRUD operations

The most common is the literal:

let obj = {
  name: '张三',
  age: 18,
  sex: '男'
}                         // create literal object

obj.girlfriend = '李四'    // add
obj.age = 20              // modify
delete obj.sex            // delete

let k = 'hello'
obj[k] = 'world'          // bracket: use when key comes from a variable

console.log(obj)

Output:

{ name: '张三', age: 20, girlfriend: '李四', hello: 'world' }

Three details:

  1. delete deletes a property, not a variable. After deleting, 'sex' in obj is false;
  2. Dot vs. bracket: dot only allows valid identifiers; brackets can take variables and any string (like obj['my-key']);
  3. Newly added properties appear after existing ones.

Also an easily overlooked rule: key order in objects. Integer keys are automatically sorted and appear first; string keys maintain insertion order:

console.log(Object.keys({ b: 1, 2: 2, a: 3, 1: 4 }))
// [ '1', '2', 'b', 'a' ]

new Object() produces exactly the same result as a literal, just different syntax:

let obj = new Object()
obj.name = '张三'
console.log(obj)   // { name: '张三' }

5. What new does behind the scenes

In practice, constructors are more common for batch-creating objects:

function Person(name, age) {
  this.name = name
  this.age = age
}

const p = new Person('张三', 18)
console.log(p.name)   // 张三

The line new Person('张三', 18) makes the engine do four things:

  1. Create an empty object {};
  2. Point that empty object's __proto__ to Person.prototype;
  3. Execute Person's function body with this bound to that new object;
  4. If the constructor doesn't return another object, return the new object.

So this.name = name actually attaches a property to the new object. This is the origin of "instance objects".

Step 2 is the key; it links the instance to the prototype, explained next.


6. Prototypes and the prototype chain

Two concepts first:

Their relationship is one rule, but extremely important:

Instance's __proto__ === constructor's prototype

Verify it:

function Person(name) {
  this.name = name
}
Person.prototype.say = function () {
  return 'hi, ' + this.name
}

const p = new Person('张三')

console.log(p.__proto__ === Person.prototype)                   // true
console.log(Person.prototype.__proto__ === Object.prototype)     // true
console.log(Object.prototype.__proto__)                         // null
console.log(p.say())                                            // hi, 张三

console.log(Object.hasOwn(p, 'name'))   // true  — own property of instance
console.log(Object.hasOwn(p, 'say'))    // false — say is on the prototype

How is a property found?

  1. Check the object itself first;
  2. If not found, go up through __proto__;
  3. Continue until Object.prototype, then up to null; if still not found, return undefined.

This is the prototype chain. It brings two consequences:

Benefit: all instances share methods, saving memory. say is stored only once, on Person.prototype, and every instance can use it.

Pitfall: shared things are also shared. If you put a reference type on the prototype:

function A() {}
A.prototype.list = []

const x = new A()
const y = new A()
x.list.push(1)

console.log(y.list)   // [ 1 ] — y is affected
console.log(x.list === y.list)   // true

That's why the spec suggests: data on instances (via this.xxx = ... in the constructor), methods on the prototype.

Some related tools:

console.log(p instanceof Person)                       // true — judged along the prototype chain
console.log(Object.getPrototypeOf(p) === Person.prototype)  // true, more standard than __proto__

__proto__ is actually an accessor property on Object.prototype (legacy); modern code recommends Object.getPrototypeOf() / Object.setPrototypeOf().

Finally an extreme case—an object without a prototype:

const bare = Object.create(null)
bare.x = 1
console.log(bare.x)              // 1
console.log(typeof bare.toString) // undefined — even toString is missing

Such an object is useful as a pure "dictionary" because it inherits nothing, so it won't conflict with key names like toString, constructor.


7. Wrapper classes: back to the opening problem

Now we can explain 'hello'.length.

var str = 'hello'
str.a = 2

console.log(str)          // hello
console.log(str.a)        // undefined
console.log(str.length)   // 5
console.log(typeof str)   // string

When the engine reads str.length, it does three steps:

  1. Boxing: temporarily creates an object with new String('hello');
  2. Reading: looks for length on the temporary object and finds 5;
  3. Discarding: the temporary object is destroyed immediately after the read, and str remains a primitive.

So the truth about str.a = 2 is: a is written to that temporary object, which is destroyed right away. When str.a is read next time, the engine creates a new temporary object, which of course doesn't have a, so it returns undefined.

Two common misunderstandings that need correction:

Misunderstanding 1: length is on String.prototype. No. length is a property of the temporary String object itself, determined by the string content. What's actually on String.prototype are methods like toUpperCase, slice, indexOf.

Misunderstanding 2: adding a property to a primitive only "silently fails", so it's harmless. In non-strict mode it indeed doesn't throw. But strict mode throws an exception:

'use strict'
const s = 'hello'
s.a = 2
// TypeError: Cannot create property 'a' on string 'hello'

The same for numbers:

const n = 123
n.a = 2
console.log(n)   // 123 — still the same primitive

Finally, distinguish between wrapper objects and primitives, a common interview question:

const boxed = new String('hello')

console.log(typeof boxed)        // object
console.log(boxed == 'hello')    // true  — comparison unboxes the object to primitive
console.log(boxed === 'hello')   // false — one is object, one is string
console.log(boxed.length)        // 5

new String() creates a real object that can have properties and live long, but it's almost never needed in daily development—except new Boolean, new Number are clear bad habits.


8. Common APIs and copying

A batch of static methods on Object, basically used daily:

const o = { b: 2, a: 1 }

console.log(Object.keys(o))     // [ 'b', 'a' ]
console.log(Object.values(o))   // [ 2, 1 ]
console.log(Object.entries(o))  // [ [ 'b', 2 ], [ 'a', 1 ] ]

const frozen = Object.freeze({ x: 1 })
frozen.x = 2
console.log(frozen.x)           // 1 — can't change after freezing (strict mode throws)
Method Effect
Object.keys / values / entries Get keys, values, key-value arrays
Object.assign(target, ...sources) Merge/shallow copy
Object.freeze / Object.isFrozen Freeze object, forbid add/delete/change
Object.create(proto) Create object with specified prototype
Object.defineProperty Fine-grained property control (enumerable, writable, getter/setter)
Object.hasOwn(obj, key) Whether it's an own property (safer than hasOwnProperty)

Shallow copy and deep copy

This is where reference types cause the most accidents:

const src = { user: { name: '张三' } }

const shallow = Object.assign({}, src)   // equivalent to { ...src }
shallow.user.name = '李四'
console.log(src.user.name)               // 李四 — original changed!

Because shallow copy only copies the first level, the user reference is copied, and both objects point to the same inner object.

Deep copy:

const deep = structuredClone(src)
deep.user.name = '王五'
console.log(src.user.name)               // 李四 — unaffected

structuredClone is the deep-copy solution now supported by browsers and Node. The old JSON.parse(JSON.stringify(obj)) also works, but it drops functions, undefined, Symbol, and turns Date into a string and RegExp into an empty object; use with caution.


9. Class is just sugar for prototypes

ES6's class looks new, but underneath it's still prototypes:

class Animal {
  constructor(name) { this.name = name }
  speak() { return this.name + ' 叫了一声' }
}

class Dog extends Animal {
  speak() { return super.speak() + ':汪' }
}

const d = new Dog('旺财')
console.log(d.speak())                 // 旺财 叫了一声:汪
console.log(d instanceof Dog)          // true
console.log(d instanceof Animal)       // true
console.log(Object.hasOwn(d, 'speak')) // false — method is on Dog.prototype

super.speak() actually goes to find the method on Animal.prototype. So once you understand the prototype chain, class, extends, super don't need separate memorization.


10. 8 self-test questions

1. What is typeof null?

'object'. It's a historical bug; to test null, use x === null.

2. After const b = a (a is an object), if you change b.n, will a.n change?

Yes. It copies the reference; both variables point to the same object.

3. Why is { n: 1 } === { n: 1 } false?

Objects compare by reference address; the two literals are two different objects.

4. Does p.__proto__ === Person.prototype hold?

Yes. The second step of new points the instance's implicit prototype to the constructor's explicit prototype.

5. What does this output?

function A() {}
A.prototype.list = []
const x = new A(), y = new A()
x.list.push(1)
console.log(y.list)

[ 1 ]. Reference types on the prototype are shared by all instances. Data should be placed in the constructor.

6. After 'hello'.a = 2, what is 'hello'.a? Why?

undefined. The property was written to a temporary wrapper object that was discarded after the read.

7. Are new String('hello') and 'hello' equal?

They are equal with == (unboxing), not equal with === (different types). typeof new String('x') is 'object'.

8. Can you change properties of an object declared with const?

Yes. const locks the variable binding, not the object content.

const c = { n: 1 }
c.n = 2      // allowed
c = {}       // TypeError: Assignment to constant variable.

11. Quick reference table

Question Conclusion
Which are objects? Only reference types are objects; primitives are not, but they can temporarily box to "borrow" methods
How do objects compare? === compares addresses, not content
How are properties found? Own → __proto__ → … → Object.prototype → null
prototype and __proto__? Functions have prototype, objects have __proto__; instance's __proto__ points to constructor's prototype
Where do methods go? Methods go on the prototype (shared), data goes on instances (each has its own)
Can primitives have properties? No. Written to a temporary object, discarded after reading
What to note when copying? Shallow copy only copies the first-level references; deep modifications affect the original object

Final three sentences

  1. Objects are reference types; assignment and comparison pass addresses, not content.
  2. Property lookup follows the prototype chain: own → __proto__ → … → null; shared methods go on the prototype, independent data on instances.
  3. Primitives are not objects; 'hello'.length is the engine's temporary boxing result, and the boxed object is discarded after use, so adding a property to it always yields undefined.

Once you understand these three, object-related problems basically boil down to remembering APIs.