JS: “function” (keyword) declaration vs expression
When you use the keyword function to define function, there are many complex issues about name-hosting and nesting functions.
const gg = function ff() { return 3; }; console.log(ff()); /* error: Uncaught ReferenceError: ff is not defined */
When is function definition a declaration?
It is a function declaration if all of the following are met:
- At top-level of source code (that is, not inside any curly bracket.) or it is at top-level inside a function.
- Not on the right-hand-side of a assignment.
/* Function Declaration */ function ff() { return 3; } console.log(ff()); // 3
Function declaration must be top level
Named function form is a declaration only if it is at top level of source code or top level inside a function body. When in elsewhere, its a named function expression.
// no function declaration happens here. The ff is treated as named function expression const gg = function ff() { return 3; }; console.log(ff()); // error: Uncaught (in promise) ReferenceError: ff is not defined
When is function expression
When you use the keyword function, and it is not at top-level of source code, nor at top-level inside a function, it has meaning of Function Expression.
// function expression, applied on the spot console.log( (function (x) { return x; })(4), ); // 4
🟢 tip: i recommend don't use the keyword function.
use Arrow Function.