0

I've been searching for two days straight but can't find the answer. Is there any advantage to using a function expression over a function declaration?

The book I'm reading (Head First JavaScript) introduces function expressions and the explanation sounds to me like it's identical to a function declaration, but then it goes on to say that they are "subtly different" -- but doesn't explain the difference!

The ONLY difference I have been able to find is that you risk getting an error when using an expression if you call the function before defining it but not if you use a declaration (due to hoisting). Declaration, 1. Expression, 0.

However, from what I understand, a declaration creates a variable using the function's name and stores a reference to the function in that variable.

Using an expression, you store a reference to an anonymous function in the variable of your choice.

If that's the case, then aren't these two examples identical in every way except the aforementioned risk of an error when using an expression due to hoisting?

Declaration:

function myFunction(name) {
    alert("Hello " + name);
}

Expression:

var myFunction = function(name) {
    alert("Hello " + name);
    }

I can call the either one with:

myFunction("John");

I can also assign either one to a different variable and then call that variable so the following would be valid in either case:

var myFunctionDammit = myFunction;
myFunctionDammit("Steve");

I can't figure out why you would EVER create a function expression when the only difference I can find is actually a disadvantage.

What situations would warrant an expression and why? What is considered best practice? Should I get into the habit of using one over the other?

There is a similar question (var functionName = function() {} vs function functionName() {}) but most of the answers there focus on addressing the technical difference (hoisting) but fails to explain WHY I would ever want to choose a function expression over declaration. Either that or I am simply failing to understand the answers.

Can someone lay it out in simple terms a beginner would understand?

Community
  • 1
  • 1
AlwaysLearning
  • 159
  • 2
  • 10

0 Answers0