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.
-
1They are immutable by design. There does not have to be a reason. Other languages are based on different decisions.trincot– trincot2021-07-25 16:43:29 +00:00Commented Jul 25, 2021 at 16:43
-
Also related: Why can't I add properties to a string object in javascript?Ivar– Ivar2021-07-25 16:45:52 +00:00Commented Jul 25, 2021 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– Bergi2021-07-25 17:21:45 +00:00Commented Jul 25, 2021 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, but that doesn't count as design). The only decision that really distinguishes languages here is whether strings are primitives or not.Bergi– Bergi2021-07-25 17:56:56 +00:00Commented Jul 25, 2021 at 17:56
-
@Bergi but objects are passed by reference. So that’s why they are mutable ?Pavan– Pavan2021-07-25 18:27:52 +00:00Commented Jul 25, 2021 at 18:27
|
Show 2 more comments