Function Declaration vs. Function Expression
What is a Function Expression?
A Function Expression is a function that is created and assigned to a variable explicitly, like any other value. Here is an example of a Function Expression below:
Once the function is stored in a variable it can be called just like a normal function. Some of the differences with a function expression are:
- They are not hoisted
- They can be used as an IIFE (Immediately Invoked Function Expression)
- They can be passed into functions as arguments
- They can be used as closures
What is a Function Declaration?
A function statement declares a function. The propose of a function is to create a list of instruction that will be used at a future time, when the function is invoked. Just like declaring a variable a function has to be declared with the function key word. Here is an example of a function declaration:
Once a function is declared it can be invoked like so:
This function is a function to calculate the area of a rectangle, which has the length and the width passed in as arguments. If a function declaration does not require arguments it would be called like so getRectArea(). One major difference is function declarations can be hoisted.
Thanks for reading.