Question

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?

Was it helpful?

Solution

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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top