0

In a JS tutorial i have come to learn that primitive datatypes are immutable. However i'm not sure as to how datatypes are immutable. Like in what way are they immutable?

Do they mean that an immutable primitive datatype can only have it's value changed by way of assignment and not with an operation?

But objects however are mutable. Can someone explain how primitive values are immutable and show an example of how properties of an object are changed in a "mutable" way?

syclone
  • 99
  • 13
  • 3
    Does this answer your question? [What does immutable mean?](https://stackoverflow.com/questions/3200211/what-does-immutable-mean) – kirjosieppo Jan 08 '22 at 00:14
  • "*show an example of how properties of an object are changed in a "mutable" way?*" - `let obj = { foo: 1 }; obj.foo = 2;` – VLAZ Jan 08 '22 at 00:22
  • @VLAZ well thats actually not true because all primitive datatypes are immutable except objects. Re-assigning values can be done in primitive datatypes as well. – syclone Jan 08 '22 at 00:41
  • @syclone that's not reassigning a variable, it's *changing* an object. Mutating it. Try it with `obj = 1` and then do `obj.foo = 2`. See if that changes the number `1`. What you're talking about is reassigning *a variable*, e.g., `x = 1; x = 2`. This does not *change* the `1` nor the `2` - it just modifies the binding. The data is intact. It's immutable, after all, so you're just changing what value a label refers to. Not changing the value. When changing an object property, the value is most definitely changed. – VLAZ Jan 08 '22 at 00:48

0 Answers0