What is the difference between a function declaration and a function expression?
Quick answer
A function declaration defines a function directly with a name, as in function double(n) { ... }. A function expression creates a function as part of an expression, often assigning it to a variable, as in const double = function(n) { ... };. Both can be called to return a value. Expressions can be named or anonymous, and the forms differ in initialization behavior, so do not assume they are available at the same point in your code. [S1] [S2]
The question, the details, the next step.
A practical checklist
Look for
function name(...)to identify a declaration.Look for a function assigned as a value, such as
const name = function(...) { ... };, to identify an expression.Check whether the function expression has its own name or is anonymous.
Check the exact form and context before relying on when a function is available.
Follow the
returnstatement to determine the value a call produces.
A few more useful answers
Does a function expression always have to be assigned to a variable?
Do the declaration and expression examples return different kinds of values?
Not in these examples. Both functions use the same calculation and receive the same input, so each returns the number 8.
Sources
References used for this guide.
- [S1] function — JavaScript | MDN developer.mozilla.org · Checked
- [S2] function expression — JavaScript | MDN developer.mozilla.org · Checked
