0

I'm struggling to see the differences and benefits between defining a function as a variable vs just defining a function with a name. When would it be better to use each type?

Simple function definition

function add(a,b) {return a+b;};
// and calling it like this when you need it:
add(5,2) // Sum 7

vs

As a variable:

add = function(a,b) {return a+b;};
// and calling it like this when you need it:
add(5,2) // Sum 7

Apologies for the rookie question. Thanks!

Edited: typos

turmeric
  • 535
  • 2
  • 7
  • 16
  • Function declarations load before any code is executed while function expressions load only when the interpreter reaches that line of code. Function expressions are also not hoisted, which allows them to retain a copy of the local variables from the scope where they were defined. – Cue May 25 '20 at 21:54
  • Not much difference between the two. Function definitions get hoisted, so you can call `add(5,2)` before the definition of `function add` in the first case, whereas you can't in the second case – Jeril Sebastian May 25 '20 at 21:56

0 Answers0