0
var b = true;
b.foo = 'whatever'; // Auto-boxing occurs?
b.foo; // undefined - why?

Can I retrieve the value of property foo now?

Ben Aston
  • 53,718
  • 65
  • 205
  • 331
  • var b has to be an object, `e.g var b = {}; b.foo='whatever'; b.foo = 'whatever' – Babajide Fowotade Aug 27 '15 at 12:54
  • No, Might be because it's a primitive type .. – Hacketo Aug 27 '15 at 12:56
  • possible duplicate of [What is the difference between JavaScript object and primitive types?](http://stackoverflow.com/questions/21933120/what-is-the-difference-between-javascript-object-and-primitive-types) – Hacketo Aug 27 '15 at 12:58
  • related too : http://stackoverflow.com/questions/5201138/why-cant-i-add-properties-to-a-string-object-in-javascript – Hacketo Aug 27 '15 at 12:59

1 Answers1

0

var b is initially set to Boolean value. to assign dot notation to a variable, it has to be a javascript Object. if b is set as var b = {}, b.foo = 'whatever'; should work. For better practice always check type of variable before switching its datatype:

var b = true;
if(typeof b === 'object'){
  b.foo = 'whatever';
}
Vicky Gonsalves
  • 11,593
  • 2
  • 37
  • 58