I will take the example of JavaScript in this article, but the same is true in many programming languages, like C#.
Basically, there are two families of variables types: primitives and objects.
Within each, you find the well-known types as list in this top image.
What is important to understand is that you can copy primitives by value or you copy object types by reference.
Value types
For example:
|
|
Value types store the actual value in memory. And the above code shows that a distinct copy of the value gretting
is created to initialize newGreeting
.
You don’t have a link in any way between the two variables.
Reference types
When you create an object, it’s stored in memory and the JavaScript uses a reference or its address in memory to find the value.
That reference is used to handling the object.
For example:
|
|
The last assignment changes the value of the property gretting.message
because both variable share the same refence in memory!
To avoid that, you must create a true copy of greeting
. That can easily be done with the spread operator (given a flat object only, nested objects require more code…):
|
|
With {...greeting}
, we assign a new object and therefore the JavaScript engine creates a new reference to store newGreeting
.
Consequently, newGreeting.message = 'Bonjour';
won’t affect the value of greeting.message
.