A value named blob.

Say we have a JavaScript value “ “.

Then if we could do something like var blob = ; what would be the meaning (semantics) of what we just asked JS to do?

We know from our previous discussion that the var keyword in conjunction with a name is used to create something called a variable. And that when we assign a value using the = operator, JS somehow put the value in the variable.

#2 is rather simplistic and indeed misleading. The meaning of “assignment” with respect to JS is more subtler than that.

What var blob = ; really means is as follows.

Create a reference (think a link) to which exists in memory. Create a variable named blob and update it with a reference to

Key idea: Assignment ( = ) creates references. Variables contain references.

We shall see the consequences of that in further detail.

Let’s consider the meaning of var thingy = blob; Note that we are still continuing the session from above and thus blob still refers to

Create a variable named thingy . Refer thingy to what ever blob is referring to. (In this case ).

Gratuitous Graphic:



Another example and more gratuitous graphics.

Consider “ ” and “ ” to be JS values.

With that, let consider the meaning of the following.

var ball, sphere;

ball = ; Note, we’re not using the var anymore as ball has already been declared..

sphere = ;

ball = sphere;

As far as we are concerned, the value that ball was originally referring to is lost. We have no way of referring to that anymore. It’s beyond our reach. JS sees this and based on the assumption that we have no use for it anymore, eats it.

Some people call this process “Garbage Collection”. But that sounds a bit haughty don’t you think?

About primitives. Primitives are assigned and manipulated via variables quite differently from the above. But the rat’s nest complexity of this topic can be simplified by thinking of primitives as immutable (unmodifiable) that are always referred to by the literal notation of these primitives. Ie: There is only one value for each primitive existing in memory. Say the number one or the string (foo) is always referred to by it’s literal syntax. 1 and "foo" respectively. You can also think of them as not being eaten by JS (garbage collected) when no variable is referring to them because of this.

Summary

Variables are more like tags than boxes.

Variables contain references that point to values.

A value can be referred by many variables.

Share this: Twitter

Facebook

Like this: Like Loading...

Tags: primitives, references, values, Variable