When we use a function's name, without parentheses, on the right side of an equal sign, what is exactly happening?

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

  1. makes enough space in memory for the number 42 and saves the location
  2. writes down the number 42 at that location, and finally
  3. 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

  1. makes space in memory for all instructions needed to perform the functionality of square
  2. writes down the set of instructions at that location, and finally
  3. 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.

the names meaning and square are pointers to the location where the data is stored in memory?

3 Likes

Thank you for this very simple, easy to understand explanation of how Functions work - Functions have been a struggle point for me but I think this has cleared things up enough for me to now understand them…

This was super helpful mate. Thanks much!