Question
If F
is the name of a function and we write F
on the right-hand-side (RHS) of an equal sign without parentheses, e.g.
const x = F;
what is exactly going on?
Answer
When we define a variable and give it a value, as in const meaning = 42;
, the computer
- makes enough space in memory for the number
42
and saves the location - writes down the number
42
at that location, and finally - makes it so that whenever we use the name
meaning
the computer remembers this location.
So when we write something like, const x = meaning
, we get that x === 42
is true
because the computer remembers the location that it originally wrote down the value of meaning
and copies that over to x
. Great. We understand this. Functions are not really different. When we write something like
function square (n) { return Math.pow(n, 2); }
the computer does something similar to the three steps above. I’ll make bold the differences. The computer
- makes space in memory for all instructions needed to perform the functionality of
square
- writes down the set of instructions at that location, and finally
- makes it so that whenever we use the name
square
the computer remembers this location.
As you can see, these points differ only slightly from the ones we first saw. So just as using meaning
on the RHS of an equal sign causes the computer to dig up the location in memory that it assigned to meaning
, in the same way const x = square;
will cause the computer to find the location in memory that it assigned to square
and makes a copy of the information at that location for the variable x
.