0

I am new to javascript and I am a little confused with the concept of immutability. Are javascript primitive variables immutable because they are accessed/ passed by value ? If this isn’t the reason, please mention.

Pavan
  • 1
  • 2
  • 1
    They are immutable by design. There does not have to be a reason. Other languages are based on different decisions. – trincot Jul 25 '21 at 16:43
  • Also related: [Why can't I add properties to a string object in javascript?](https://stackoverflow.com/questions/5201138/why-cant-i-add-properties-to-a-string-object-in-javascript) – Ivar Jul 25 '21 at 16:45
  • "*Are primitive variables immutable because they are accessed/passed by value?*" - no. Everything in JavaScript is passed by value, there are no function calls with references to variables. – Bergi Jul 25 '21 at 17:21
  • @trincot I've never seen languages where primitive values are mutable, tbh. (Uh, [Java's integer wrappers can be mutated with reflection](https://codegolf.stackexchange.com/a/28818/7588), but that doesn't count as design). The only decision that really distinguishes languages here is whether strings are primitives or not. – Bergi Jul 25 '21 at 17:56
  • @Bergi but objects are passed by reference. So that’s why they are mutable ? – Pavan Jul 25 '21 at 18:27
  • @Pavan [No, even if that's a common misconception](https://stackoverflow.com/a/5314911/1048572). Objects are reference values, i.e. their properties are mutable and multiple values (objects) can reference the same property set (i.e. "be the same object"), but they're still passed by value to function calls like everything else. Reassigning a parameter variable does never change a variable used as an argument, it will still hold the same object afterwards. – Bergi Jul 25 '21 at 18:31
  • @Bergi. Thanks for the explanation and link you shared. Finally, Javascript is purely pass by value and primitives are immutable by design – Pavan Jul 25 '21 at 19:48

0 Answers0