Glossary / Function declarations

Function declarations

A function declaration defines a named function in its surrounding scope using function name(...) { ... }. The declaration binding is instantiated before ordinary statement execution, so the function can generally be called earlier in that scope. Declarations work well for stable named operations and often provide clearer stack traces than anonymous callbacks.

Declaration versus expression

announce(); // callable here
function announce() {
  return "ready";
}

// A function expression assigned to const is not available before initialization:
// compute();
const compute = function () { return 42; };

The declaration creates a function binding during declaration instantiation. The expression creates a function value when its initializer executes; the const binding itself is subject to the temporal dead zone. A named function declaration can refer to itself recursively by its name.

Top-level scope depends on the source type. In a classic browser script, some declarations interact with the global environment and global object; in an ES module, declarations remain module-scoped. Block-level function declarations in old non-strict scripts had legacy compatibility behavior, so modules and strict code are more predictable. Avoid relying on declaration ordering just because the engine permits it.

Function declarations are hoisted, but assignments inside their bodies are not executed early. Multiple same-name declarations and interactions with var have nuanced rules; linting can prevent ambiguous duplicates.

Interview questions

  1. Can a function declaration be called before its source line? Generally yes within its scope, because its function object is initialized during instantiation.
  2. How does that differ from a const function expression? Its value is assigned when the initializer executes, after which the const binding is usable.
  3. Does module-level function declaration create a global property? No; modules have their own top-level scope.
  4. What does hoisting not do? It does not execute the body or move later assignments earlier.

References