##Functions in a Nutshell
I love Haverbeke’s description of a function as “a piece of program wrapped in a value” to be used and reused later. But the mathematical definition of a function that I learned in school still applies: “a relation that associates an input to a single output according to some rule.”
A function is often described as a black box that turns one thing into another thing. Once the black box has been created, we can safely ignore its inner workings and focus instead on its inputs and outputs, treating the black boxes as building blocks to create more complex systems while keeping them modular and extensible.
Yesterday I noted my confusion over the different ways to define functions:
And according to this StackOverflow post, the first version (or function definition) is also called an “anonymous function expression”. Whew, what a mouthful of vague terms!
Anyhow, the most important difference between the two can be summed up with one word: hoisting. Another excellent book called You Don’t Know JS has a great chapter on hoisting, with the following example:
The above code works because declarations are run before the rest of the code. As Haverbeke writes, “This is sometimes useful because it gives us the freedom to order code in a way that seems meaningful, without worrying about having to define all functions above their first use.”
He also warns not to use function declarations inside conditional blocks or loops, because browsers don’t handle it consistently and so things are likely to break! I’ll definitely try to remember that.
Hurray, I now (sort of) understand the difference between function definitions and function declarations!
But in answering that one question, I’ve uncovered many more!
- What is variable scope? The word “scope” appears in every article I read about “hoisting”, so I better figure out what it means!
- What’s the difference between a statement and an expression? I don’t fully understand either of those terms.
I have plenty more questions, but it’s Friday and I want to do some other fun stuff tonight! So I think I’ll give my brain some time to digest what I read today.