Variable binding: (re-) assignment, argument passing, `let`, scope

Glad to hear it.

Here’s another observation that may help. If you want to, you can think of variables as pointing (in the sense of C pointers) to objects, which you can think of as living in memory. When you think about x = 1; y = x; x = 2, however, you should not interpret x = 2 as putting 2 in the location that x points at. That would amount to mutating the (immutable) value 1 and would result in y == 2, which is not what happens. Instead, you have to interpret x = 2 as changing the pointer x to point at the location of the object 2; the object 1 remains where it is and y still points at it.

This mental model is valid regardless of the mutability of the objects being pointed at. The model is, however, more literally true for mutable objects since they are generally associated with a particular memory location. Immutable objects, on the other hand, can be copied around since they cannot change, and are not generally meaningfully associated with a particular location in memory.

All of this is completely unrelated to scope. Scope is about determining where the name x means the same thing and where it means something different. There’s not really a pointer or memory analogy for this and I think that trying to map it to that is likely to go poorly.

5 Likes