What are the advantages of function expressions?

So does someone have an example of why I’d ever want to use a function expression over a function declaration?

9 Likes

I’m a little confused as to the application for Function Expressions, at least in the way it’s being shown in the exercise and my current understanding.

At a glance it appears redundant to declare a variable to hold a function when a function can just be declared on it’s own. Is it maybe related to memory usage throughout a larger program?

I think an example of a practical use case would set me straight.

Insight would be appreciated.
Thanks!

3 Likes

This is an article from 2015, before arrow functions were adopted into regular use, but it can apply to them, as well, for the most part.

Quick Tip: Function Expressions vs Function Declarations

Conslusion
As we’ve seen, function expressions don’t offer much that can’t be achieved with function declarations, but using them can often result in cleaner and more readable code. Their widespread use makes them an essential part of every developer’s toolbox.

15 Likes

you can see here :


at the part called function hoisting.

Then at this part of lesson from codecademy
https://www.codecademy.com/courses/introduction-to-javascript/lessons/functions/exercises/function-expressions?action=resume_content_item

it said :

Unlike function declarations, function expressions are not hoisted so they cannot be called before they are defined.

for me that is the advantage from function expressions.

5 Likes

You can also assign an anonymous function to be the value of a variable, for example:

const myGreeting = function() {
  alert('hello');
}

This function could now be invoked using:

myGreeting();

This effectively gives the function a name; you can also assign the function to be the value of multiple variables, for example:

let anotherGreeting = myGreeting;

This function could now be invoked using either of:

myGreeting();
anotherGreeting();

But this would just be confusing, so don’t do it! When creating functions, it is better to just stick to this form:

function myGreeting() {
  alert('hello');
}

You will mainly use anonymous functions to just run a load of code in response to an event firing — like a button being clicked — using an event handler. Again, this looks something like this:

myButton.onclick = function() {
  alert('hello');
  // I can put as much code
  // inside here as I want
}
5 Likes