Contents:
- Declarative vs Expressive Functions
- Function Hoisting
- Anonymous Functions
- Arrow Functions
- Pure Functions
- IIFE — Immediately Invoked Function Expression
1. Function Declaration vs Expression
In JavaScript a function is just a value. This means that we can create functions that are named or unnamed. Named functions are function declarations. Unnamed functions are function expressions and look like this:
All we are doing here is taking a function (a value) and setting it equal to some variable. Because the function itself does not have a name it is called an anonymous function. We can call the variable “addTwo” to use the function.
A function declaration looks like this:
2. Function Hoisting
Have you ever made a function call and then later in the code declared the function and wondered why it worked? This is called function hoisting. It looks like this:
Function declarations are hoisted to the top of their scope while function expressions are not.
3. Anonymous Functions
To put it simply, anonymous functions are unnamed functions. The advantage to using anonymous functions is it helps to simplify your code. The disadvantage is that if there is an error in the call stack the error message will not contain a function name and be harder to debug.
We can use anonymous functions as arguments for other functions. Like so:
If you want a function to be immediately invoked (run) after its declaration we can create an anonymous function like this:
Arrow functions are also anonymous functions. More on that in #4.
4. Arrow Functions
Since the release of ES6, arrow functions have been around. A shorter syntax for creating an anonymous function, arrow functions are useful to simplify and shorten code.
Lets take this function:
With arrow syntax it turns into this:
5. Pure Functions
Pure functions don’t change or rely on code outside of the function. A pure function takes in parameters and returns a value. In other words, it has no side effects. If parameters of equal value are passed to a pure function, it will always return the same output.
Functions that have side effects or rely on outside code are called impure functions.
6. IIFE — Immediately Invoked Function Expression
An IIFE is a function that is invoked as soon as it is declared. We do this by appending parenthesis ( ) at the end of a function declaration.