← Back to home

Explaining functions

I was teaching some basic JavaScript to a friend the other day. Some of the things, like variables, assignments, basic arithmetics were very easy to explain. It got tricky in two concepts:

  1. What is the difference between console.log(myFunction) and console.log(myFunction())? The notion of passing a function as a parameter vs passing a result of a function invocation was very difficult to explain. We spent probably an hour just on that. I tried many analogies, and the one that clicked with my friend was the same analogy we use to teach the pointers: passing function as a parameter is like giving an address to a house, and its result is like having this house right in front of you. I don’t think it’s the closest and the most accurate metaphor, but it worked.

  2. How to explain what document.getElementById does? To my friend, it wasn’t clear that though both the HTML markup and JavaScript code are in the same file, JavaScript needs to have special code (indirection) in order to access HTML elements. Again we used several metaphors, and the one that clicked was that HTML and JavaScript by design are completely two separated worlds that have little to do with each other; however it would be helpful for these two worlds to interact with each other, and that’s why we have these bridges like getElementById.

I was very delighted that everything we needed to make programs and see the results (btw, with a very fast feedback loop) were just a text editor and a browser. Open a file, reload it once in a while, and you have a very productive set up.

Last edited on May 28, 2019