Solving the Reference Problem in JavaScript!

Solving the Reference Problem in JavaScript!

Primitive types:

Basically, if it’s storing a simple piece of data, it’s stored simply. When you set a variable with this type, the variable is that exact value and that’s all. If you change that value, the variable simply becomes a new value.

JavaScript has 5 Data types that are passed by value: Boolean, null, string, undefined, Number, Known as primitive types.

Reference Types or Non-Primitive or objects:

When you create an object, that value is not directly assigned to the variable. Instead, a reference to that value is what gets set. All that variable knows about is the location of the object, not the object itself.

JavaScript has 3 Reference types that are passed by reference: Array, Function, and Object. These are all technically Objects or (non-primitive).

Code that copies a value is where it counts

color1 is assigned the string value ‘green’, which means the variable color1 is essentially the same as just a string ‘green’. When we use color1 to assign a value to color2, it would’ve been the same as if we literally assigned it a string value. So when we reassign color1’s value, it has absolutely no impact on color2. Both values were always just saving strings, they had no lasting bonds between them. This is not the case with reference types. Look:

We never assigned car2 a brand property, yet it has one. Despite the situations looking the same as our primitive example, the behavior is the opposite. That’s because car1 was never assigned the value of the object, only the reference to it. So if you change car1, that will alter the same spot in memory that car2 is looking at.

Solving the reference problem

By adding that brand property, we permanently altered the original object. That is called a mutation, and it’s not great when we accidentally do it to more than our intended target. To get around this, we just have to create a new reference to a new object. That way, each variable will point to its own object and not have any overlap. The most common approach is to use Object.assign or the spread operator. For brevity, let’s use a spread:

Note : Objects are mutable, meaning they can change (unless you *freeze* them.) Primitive types are immutable i.e you can’t actually mutate the number 1 into 2, you just replace the value. Meaning we didn’t change our ‘green’ string, we just straight up replaced it with a new string, ‘purple’.

Original Article