How to explain the difference between a variable and a key in a key-value pair

conceptslanguage-agnostic

Variables and the keys in key-value pairs are both identifiers for values, so, on a conceptual level, these seem very similar ideas.

How would you explain the difference between these two concepts?

  • Is it that key-value pairs are used in collections?
  • Is it that variables point to a memory location?
  • Or something else?

(If I look at code, I'm instinctively aware of the difference, the question's more about how to explain it which doesn't seem too obvious given that they do similar things.)

Best Answer

There is no real difference.

We can think of a variable as a name that maps to some value. All visible variables together make up the environment. This observation is important in some theoretical discussions, and is also used in some language implementations (mostly dynamic languages like Ruby). Especially objects can be represented in different ways – some may be choose static structs where an object member is a field in that struct (e.g. C++), others may use dynamic dictionaries which contain all members as key-value pairs (e.g. JavaScript).

The nice thing is that these are mostly equivalent to each other: you can see one as a generalization, the other as a performance optimization.

In sane languages, the environment is known at compile time, whereas the keys in some dictionary are generally only known at run time. This is the only useful difference: when the key of some mapping is known.