ELI5: Why use a function declaration, expression, or an IIFE in JavaScript?

ryansmith

Ryan Smith

Posted on February 23, 2019

ELI5: Why use a function declaration, expression, or an IIFE in JavaScript?

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() {
  ...
}
Enter fullscreen mode Exit fullscreen mode

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() {
  ...
}
Enter fullscreen mode Exit fullscreen mode

I have also seen this done with an arrow function.

const calculateAverage1 = () => {
  ...
}
Enter fullscreen mode Exit fullscreen mode

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 () {
    ...
})();
Enter fullscreen mode Exit fullscreen mode

Thanks!

💖 💪 🙅 🚩
ryansmith
Ryan Smith

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