2

Recently, while reading the book "Eloguent Javascript" by Marijn Haverbeke, in chapter 2: Program Structure, section 2: Variables, I came across this statement:

They (variables) do not contain values; they grasp them

He then goes on to use the analogy of an octopus with many hands to demonstrate how variables grasp values.

This is the first time I'm seeing such a characterisation of variables. In other books and/or articles I've read, variables have usually been likened to boxes (in the computer's memory) containing values.

My question is: which is correct?

  1. Variables can be thought of as boxes containing values
  2. Variables don't contain values, they only grasp them

Am I the one getting it all wrong in my head? Do both explanations mean the same thing?

NaijaProgrammer
  • 2,892
  • 2
  • 24
  • 33
  • 1 or 2, why/does it matter? – Tushar Jul 09 '15 at 10:38
  • 1
    They're just analogies. Variables are neither boxes nor tentacles, at the end they're just electrical signals inside the computer. You can use whatever mental image you want. – JJJ Jul 09 '15 at 10:39
  • I think the analogy(ies) are useful for understanding the difference between a variable that holds a scalar value versus a variable that holds a reference to an object. Clearly, there's at least a logical (if not real) distinction between both cases. Am I right? – NaijaProgrammer Jul 09 '15 at 10:43

1 Answers1

1

I think what Haverbeke is trying to say by this statement is that all variables that are not primitives in javascript are references.

In answer to your question, both explanations are correct but apply to different contexts.

Let's look at the boxes approach. We can think of variables as boxes that contain PRIMITIVE values. In javascript these are Number, String, null, undefined, and Boolean.

Now, we come to the octopus approach. The rest of the things in javascript are too big to fit in boxes. Let's say you wanted to store your house in a box. It wouldn't fit at all. That's why Haverbeke says the variables grasp values. There is a large field where all of your things that are too big for boxes sit. You still have a box, but it doesn't contain the thing. Instead, it contains the coordinates in the field for where you can find your value. This is called a reference to the object, or the address of the object in memory (the field).

The grasping concept is designed to ensure that you don't think passing an object will copy it over. When you pass an object from one variable to the other, the object is the same. You have two boxes with the same address. Change the object from either of those variables will change both variables.

Strikeskids
  • 3,932
  • 13
  • 27