The conundrum of value and reference types, visualized.

One of the proverbial things to understand in programming is the mouthful of why when we let a = 1, and we let b = a, and then we change a = 5, why b is still 1. Visually articulated:

In an attempt to understand them better, I created a one-sheet visualization of the matter at hand. But if I could sum up what solidified understanding, it was a small change in language.

In essence, primitive values (i.e. things like strings, numbers, and booleans) are stored by storing the value – emphasis on the the. This means that the actual value is stored inside the variable. So when I tell the computer to store a in b, I’m not storing a link from b to a, but a copy of the value originally stored in a.

More complex values (i.e. things like arrays or objects, or in lay terms, collections of primitive values) are stored by stored the reference to the value. This means that what gets stored in the variable is a reference to the location in memory where the data is stored. It is, therefore, in this case that changing the data in one variable gets reflected on both variables.

Hopefully, the visualization below makes things clearer:

Other posts about:
You're subscribed!
Oops! Something went wrong while submitting the form.