When to Use Function Expressions?
Tags: function, webdev, javascript, beginners
Published: 2023-01-19 15:57:40

For a beginner, it’s hard to choose between function expressions and function declarations sometimes because differences like naming or hoisting are not enough.

If you have not read it yet, make sure to read the previous post about the [differences between function declarations and function expressions](https://dev.to/catherineisonline/function-declarations-function-expressions-2o5k).

There are a lot of cases where you need to use function expressions, let’s go through each of them.


## IIFE (Immediately Invoked Function Expressions)

As the name suggests, function expressions are used when we want to create an immediately invoked function, a function expression. During immediately invoked function expressions, the function is created and called at the same time. It’s useful when you don’t want to create any variables where you need to save functions.

To create an IIFE you need to create a function inside a parenthesis and then append **()** which will execute the function. The parenthesis is what makes the function become a function expression. 

In the image below, we are using an invalid function because it does not have a name and it is not saved as a value inside a variable. If we used it separately without parentheses it would throw a syntax error “Function statement requires a name”.
However, while using the parentheses, we don’t need a name because it becomes a function expression.
 
You can actually name the function anyway but it doesn’t mean you can invoke it again later, so the name is kind of useless in this case.


![IIFE](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ivn5x5np7veg47k4fvxo.png)


You can also shorten it and create an arrow function


![IIFE](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gb322tj88ae1fheqkahq.png)


And you can also place the invoking parenthesis **()** inside the parentheses



![IIFE](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w28ona6qxgpvv10mdze8.png)


## Callbacks

A callback is a function that is used inside another function as an argument and will be invoked once the main, outer function completes a specific route.

If you have not yet, read my post about [callbacks](https://dev.to/catherineisonline/javascript-callbacks-24cp).


Which function do you think will be a function expression? The main, parent function, or the callback function we placed inside it?
The callback function.


Let’s take a simple example of mapping through an array


![Map through array](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/levcoari4wlq6tpgcn8o.png)


What will be the output?
We will see an output of each fruit name in the array.

The **getFruit** function is a variable that stores a function expression. Yes, we can also use a function declaration but if you are not going to use this function anywhere, there is no point. The reason you name something is because you want to access it at some point.

We can improve this approach if we are using this getFruit variable only once and we don’t need it anywhere else anymore.

We don’t want to create an unnecessary variable in the global scope which will decrease readability and make it harder to debug code when it becomes more complex. If you can use the function just once inside another function and don’t really need it anywhere else, what is the point to save it anywhere, right?

In order to get rid of the extra variable we can write the function expression directly inside the main function.


![Function expressions as callbacks](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ornxjzx804j8c2kefkyr.png)



## Closures

If you already know what is closure [skip this](#skip)

Let’s say we created a function that is created inside another function. This inner function will have access to the variables created inside its outer/parent function.
When inner functions aka nested functions have access to the parent scope, it’s called lexical scope.


![Lexical scope](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4letywubo6h02fu2gkrd.png)


The closure has almost the same explanation. It’s a feature when an inner function has access to the outer function scope even after the parent function has closed -  returned something.
It’s a combination of a function and lexical scope in which this function was declared.

Let’s change the code above a little bit. Instead of calling the inner function we are going to return it.


![Closure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8i8j0g8hbkxp9f6ytw5x.png)


What will happen is that console is going to show only the first statement which was created in the outer function and doesn’t show the **countFruit()** statement.
So the inner function wasn’t called, it’s returned and saved in the result variable. 
The outer function just closed, returned the result.

**If you are not familiar with a return, the return ends the function execution and returns a value we specified.**


Our inner function is saved inside the result now and what should we do?
We should call this result function so it executes the value it holds, the inner function.



![Closure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9uw606of4c1oncazb220.png)


Did you notice what I added?
I called the result where the inner function was saved.





The function **myFruit** is the outer function I mentioned earlier.
The function **countFruit** is an inner function, a closure in this case, and will output “I have 4 types of fruit”.

If we try to call **countFruit** function outside the **myFruit** function it will throw an error that it’s not defined. So the closure will stay available inside the outer parent only.




Let’s get back to function expressions!

### Where and why can we use function expressions in closures?<a name="skip"></a>

Instead of naming an inner function and then returning its name, you can directly return the function without naming it or saving it in any variables.

So as a result we will get this


![Function expression in closure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fopwsr5nlgbdfbuo1o1p.png)




To summarize, here are the reasons to use function expressions:

1. You want to pass a function as an argument and not going to use it anywhere else
2. You need a function that is not hoisted
3. You don’t need to use a function later so no need to name it
4. You want to have better control over when to invoke a function