ELI5: Why use a function declaration, expression, or an IIFE in JavaScript?
Ryan Smith
Posted on February 23, 2019
I have seen functions in JavaScript declared in different ways. I have been trying to look up why, but answers that I have found only seem to state the difference between them but not the advantages of each.
My question for DEV users is why use one style over the other? What are the benefits over a classic function declaration? What are some code examples that show this?
Consider the examples below.
Function Declaration
To me, this is the "standard" way to define a function.
My understanding is that a function declaration is hoisted, so it can be called before the function is defined. I expect a function to behave that way, so this is my preferred way to create a function.
function calculateAverage() {
...
}
Function Expression
A function expression assigns the function to a variable.
My understanding of a function expression is that it will not be hoisted so it can only be executed after it is defined, but I'm unsure of why that would be useful.
const calculateAverage1 = function calculateAverage() {
...
}
I have also seen this done with an arrow function.
const calculateAverage1 = () => {
...
}
Immediately Invoked Function Expression (IIFE)
An IIFE will run as soon as it is defined.
This one, I'm not too sure on. Why put that code in a function? It allows the creation of a scope, but I'm not sure when that would be useful.
(function () {
...
})();
Thanks!
Posted on February 23, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
February 23, 2019