What is a function?

. 1 min read

I love mentoring at Codebar Sydney, because I get asked some really tough questions from beginners. Recently I was asked, "What is a function?"

The longer you have been coding, the harder this question is to answer. I've been writing functions for so long, I can't imagine a world without functions.

To the complete beginner, functions can seem like unnecessary duplication. We started off with a little JavaScript Hello World.


Then the exercise suggested we define a function.

function sayHello() {

Even worse, when we ran the file... nothing happened. Do you know why?

...because we didn't call the new function with magic words sayHello().

The idea of defining a function and then calling it later is a genuinely strange, new idea. Talking to machines is weird and takes a while to get used to. My student asked me, why should we bother defining a function and then calling it, if I could just call console.log directly? What a great question!

I could have launched into a detailed discussion about code reusability, scope, and control flow, but that's a bit too much for someone's first day of programming. I think the best approach in this case is to play with more function exercises. It's easier to show the usefulness of functions rather than trying to think of the perfect explanation.

Photo by Paweł Czerwiński on Unsplash.