0

I know, that all data types (primitives) in Js except objects are immutable. So we can't do something:

let str = 'str';
str[0] = 't'; //error in strict mode

But we can do following:

let str = 'str';
str = null;

why this works and why primitives are immutable and objects are mutable? I want to know what happened "under hood" (deep explaining).

John Doe
  • 73
  • 6
  • 1
    You're assigning to the variable, not mutating the string value. If you want a non-assignable variable, use `const`, but this has nothing to do with the primitive-vs-object dichotomy. – Bergi Jul 04 '22 at 15:51
  • `str = null` assigns a different value to `str` but does not mutate the original string value – derpirscher Jul 04 '22 at 15:52
  • Ok, but why primitives are immutable (in deep exlporer)? – John Doe Jul 04 '22 at 15:54
  • 1
    @JohnDoe Because they represent mathematical values. You cannot change the value of 5 to mean something different than 5. – Bergi Jul 04 '22 at 16:03

0 Answers0