Declarations Hoist But Function Expressions Do Not

Function declarations are callable before their definition line, while function expressions follow const rules and throw a ReferenceError if called early.

JavascriptData Integrity

Code

javascriptsnippet
23 lines
// Function declarations are fully hoisted: the binding exists and is
// callable from the start of the scope, even above the declaration
console.log(declared());

function declared() {
  return 'declaration hoisted';
}

// Function expressions follow const rules: the binding is hoisted but
// uninitialized, so calling before the assignment throws
try {
  expressed();
} catch (error) {
  console.log(error.constructor.name);
}

const expressed = () => 'expression not hoisted';
console.log(expressed());

// var-assigned function expressions read undefined before assignment
console.log(typeof legacy);
var legacy = function () { return 'var assigned'; };
console.log(typeof legacy);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

declaration hoisted
ReferenceError
expression not hoisted
undefined
function

How it works

Read it this way: everything runs through the functions expressed and declared, doing all the work.

What to watch for

  • Zero-fetch snippet: every identifier resolves inside the language distribution.

Using it

The signature doing the primary work is const expressed = ()

Key statements worth quoting

var legacy = function () { return 'var assigned'; };
const expressed = () => 'expression not hoisted';
return 'declaration hoisted';

Interactive Tools for This Topic

FAQ

Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. The file defines `expressed`, `declared` at load time.