It’s a common thought that primitive and non-primitive data are treated differently in javascript, but it just ain’t so.
Primitives are things - strings, numbers, Booleans, null
, undefined
and the like. These are simple things, and there are two things to note: they don’t contain other things, and they’re immutable. Once they’ve been placed in memory and as long as something is referencing them, they do not change. ever.
Non-primitives are collections of things - arrays, objects, Sets, Maps and the like. These are “complex” things, in that they contain other things, but it is important to note that, once a non-primitive has been placed in memory, that non-primitive is also immutable. While we can change the contents of that thing, the thing itself, the initial reference for the container, that is fixed once in memory and for as long as something is aware of it.
So if we have two variables, like this:
let a = "Euripides";
let b = a;
// at this point, they both point at the
// same memory location!
// but what happens next?
b = b.toUpperCase();
With that last line, we explicitly replace b
with a new value, at a different memory location, leaving a
looking at the original. So because primitives are immutable, when we evaluate the new result it will be a completely separate memory chunk.
With non-primitives, the result is similar:
let a = ["a","b","c"]
let b = a;
// at this moment, both point to the container,
// and to the same container.
// if we explicitly assign something:
b = b.map( char => char.toUpperCase() )
Again, we used the assignment operator (the =
) in that last line, explicitly replacing b
with a new array*. They are separate now, with no knowledge of each other.
Non-primitives differ from primitives only in that you can muck with the things they contain - because, while the container is immutable, it’s contents may not be.
It’s a bit confusing - an array of strings, internally, is simply an array container with a bunch of "pointers"telling us where to find each array item in memory. So While the container may be immutable, the outer box, we can still point those internal pointers at different memory locations, mutating the innards of that array.