Use Before Define

ID

javascript.no_use_before_define

Severity

high

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Reliability

Language

JavaScript

Tags

reliability, scope, tdz

Description

Reports references to a let, const, class or interface binding that occur before the binding’s declaration in source order, when the reference and the declaration share the same function scope.

let, const and class bindings have a temporal dead zone (TDZ): the runtime throws ReferenceError on any read between the start of the enclosing block and the declaration line, even though the name appears in the scope chain. var and function declarations are not reported because they are hoisted with usable values.

Rationale

// Bad — `value` is in the TDZ.
function bad() {
  console.log(value);
  let value = 5;
}

// Bad — class TDZ.
function alsoBad() {
  const m = new Model();
  class Model {}
}

Cross-function references are not flagged because the inner function only runs when invoked, by which point the binding is initialised:

// Good — inner runs after `later` is set.
function makeReader() {
  return () => later;
  let later = "ok";
}

Remediation

Move the declaration above its first use, or — when ordering is hard to follow — extract the late-bound value into a function so the reader sees a clear "declared then called" structure.