Immutability of primitives

All primitive values are immutable, meaning that you cannot mutate their values. This is a core part of their primitiveness. You cannot, for example, change the number value of 3.14 to 42, or change the value of a string to its uppercased variation.

But I can change the value of a string to its uppercased variation! You may be confused right now if you recall being able to do this. But there is a crucial distinction to be made here between the reassignment of variables to new primitive values, which is fully possible (and likely what you're remembering), and the mutation of primitive values, which is not possible.

When we reassign a variable, giving it a new value, we are not changing the value itself; we are only changing which value the variable refers to, as shown here:

let name = 'simon';
let copy = name;

// Assign a new value to `name`:
name = name.toUpperCase();

// New value referred to by name:
name; // => "SIMON"

// Old value remains un-mutated:
copy; // => "simon"

Note how copy has remained lowercase. The primitive value simon has not been mutated; instead, a new primitive value has been derived from it, via the toUpperCase method, and then assigned to the variable that previously held the lowercase variant.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.111.92