2

I would like to understand why it is allowed to assign a property on a string or other primitive, even though javascript never stores that value.I know that "xyz" is not the same as Object("xyz"), but look at here

var o = "xyz";
o.value = "foo bar";
alert(o.value); // alerts "undefined"

The value property stays undefined right after being assigned. When o is an object, the value property is assigned properly and returned in the alert statement. When o is undefined, assigning the property results in a TypeError. But when o is a string, nothing happens at all, the assignment is simply ignored. Ok, in my example o is a variable, but also "xyz".value = "foo bar" is perfectly legal?

Tony
  • 2,043
  • 2
  • 12
  • 5

1 Answers1

4

Strings are not objects. This:

 o.value = "foo bar";

means:

  1. Convert the string value of "o" to a String instance
  2. Set the property "value" of that instance to "foo bar"
  3. Throw the String object away.
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • is there any *rationale* behind this? – Karoly Horvath Jan 28 '14 at 20:27
  • @KarolyHorvath well, in JavaScript the type "string" is not the same as the type "String". I don't know what the rationale is; String instances (like Number instances) are immutable, so it's not clear why they ended up being distinct. Since JavaScript was designed in such a hurry, it's probably pointless to look for deep meaning :) – Pointy Jan 28 '14 at 20:28
  • That's what I thought. It's just that it's easier (for me) to remember something if it makes sense ;) – Karoly Horvath Jan 28 '14 at 20:31
  • @KarolyHorvath ha ha definitely. There's probably some performance argument to be made; letting the runtime complete "own" the nature of a string constant probably makes some optimizations easier. – Pointy Jan 28 '14 at 20:32
  • actually I was asking about the auto conversion to String... or more precisely, in this particular example. because it looks completely pointless. – Karoly Horvath Jan 28 '14 at 20:51
  • 1
    @KarolyHorvath ah, well because lower-case "s" strings are **not** objects, if it didn't auto-box the string in a String then the expression would have to be an error. The `.` and `[ ]` operators are defined such that the left-hand side is *always* coerced to an Object type. – Pointy Jan 28 '14 at 20:55
  • ah, that makes perfect sense. thank you. – Karoly Horvath Jan 28 '14 at 20:56
  • @KarolyHorvath right. Since the coercion is basically invisible, the spec says that an implementation is free to avoid doing it if there's a short-cut. However, it'd still be true in this case that after the assignment, there's no object hanging around and so there's nowhere to find that property. I suspect a modern JavaScript runtime might simply ignore that statement altogether! – Pointy Jan 28 '14 at 20:59