0

Do variables have properties?

The obvious answer should be NO. If I try to assign a property to a variable, it should give an error. Right?

If I do something like:

 var someVariable = 'Cat';
 someVariable.eyes = 'two';   //Gives no error!

alert(someVariable.eyes);     // alerts 'undefined' instead of giving an error!
Navneet Saini
  • 934
  • 4
  • 16
  • 33
  • In `someVariable.eyes` someVariable holds a String, so isn't that attempting to assign to the String object's .eyes? – Patashu May 25 '13 at 04:12

2 Answers2

3

Variables don't have properties, but their values do. (If the value's an object, anyway.) In this case, you're trying to set the eyes property of the string currently referenced by someVariable.

It won't work in this case, though. Since primitive values don't have properties, JS will convert the primitive string value into an object and set the property on that object, which pretty much immediately gets silently discarded. The end result: the primitive string remains unmodified.

cHao
  • 84,970
  • 20
  • 145
  • 172
1

"Variables" don't actually exist (except strictly within the definition of a scope), only objects. And string objects can't have arbitrary properties assigned by default.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358