1

I tested this today and I don't understand the behaviour. For me, that should be an error.

const a = 1;
a.test = 1;

console.log(a)
console.log(a.test)

Someone have the answer ?

  • 3
    Short answer: because (almost) everything is an object - see the dupe for more information. Long answer: Because the JS data typing model was built on a Friday afternoon and everyone was already drunk. – Rory McCrossan Sep 16 '22 at 13:59
  • 3
    When you use a primitive like an object (like calling the `toString` method), it's actually converted to the object counterpart (i.e a number to the `Number` object). Your changes are then on the object counterpart. After that, the object counterpart is discarded. – kelsny Sep 16 '22 at 14:00
  • Probably something around the fact that everything is an object. EDIT: caTS did a much better job of what i was trying to say. – ste2425 Sep 16 '22 at 14:01
  • @ste2425 not everything is an object. That's absolutely the wrong mental model to use. It's not useful as a shorthand, since it then supposes that rules that are applicable for object would apply to primitives or vice versa. – VLAZ Sep 16 '22 at 14:03
  • @RoryMcCrossan `and everyone was already drunk. `,, oh in that case I think I'd better get some bears, as the JS object model goes down in my books as one of the best data structures in any language.. :) – Keith Sep 16 '22 at 14:06
  • @VLAZ correction then, because most everything *Leads* back to an object. – ste2425 Sep 16 '22 at 14:30
  • @ste2425 which is still incorrect - `null` and `undefined` aren't and don't have object representation. And I don't see how it's useful to think of symbols as having connection to objects. Seems weird. – VLAZ Sep 16 '22 at 14:38
  • @VLAZ that's why i said most. It is a generalization. However i will bow out to your better judgement. I can see I'm fighting your "got-to-be-right-itus". – ste2425 Sep 17 '22 at 14:47

1 Answers1

0

you can define properties pretty much anything, but in this case you are assigning it to a number which doesn't actually hold properties.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445