noInvalidUseBeforeDeclaration
Summary
Section titled Summary- Rule available since:
v1.5.0
- Diagnostic Category:
lint/correctness/noInvalidUseBeforeDeclaration
- This rule is recommended, which means is enabled by default.
- This rule doesn’t have a fix.
- The default severity of this rule is error.
- Sources:
- Same as
no-use-before-define
- Same as
@typescript-eslint/no-use-before-define
- Same as
Description
Section titled DescriptionDisallow the use of variables and function parameters before their declaration
JavaScript doesn’t allow the use of block-scoped variables (let
, const
) and function parameters before their declaration.
A ReferenceError
will be thrown with any attempt to access the variable or the parameter before its declaration.
The rule also reports the use of variables declared with var
before their declarations.
Examples
Section titled ExamplesInvalid
Section titled Invalidfunction f() { console.log(x); const x;}
code-block.js:3:11 parse ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ Const declarations must have an initialized value.
1 │ function f() {
2 │ console.log(x);
> 3 │ const x;
│ ^
4 │ }
5 │
ℹ This variable needs to be initialized.
function f() { console.log(x); var x = 0;}
code-block.js:2:17 lint/correctness/noInvalidUseBeforeDeclaration ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ This variable is used before its declaration.
1 │ function f() {
> 2 │ console.log(x);
│ ^
3 │ var x = 0;
4 │ }
ℹ The variable is declared here:
1 │ function f() {
2 │ console.log(x);
> 3 │ var x = 0;
│ ^
4 │ }
5 │
function f(a = b, b = 0) {}
code-block.js:1:16 lint/correctness/noInvalidUseBeforeDeclaration ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✖ This parameter is used before its declaration.
> 1 │ function f(a = b, b = 0) {}
│ ^
2 │
ℹ The parameter is declared here:
> 1 │ function f(a = b, b = 0) {}
│ ^
2 │
Valid
Section titled Validf();function f() {}
new C();class C {}
// An export can reference a variable before its declaration.export { CONSTANT };const CONSTANT = 0;
function f() { return CONSTANT; }const CONSTANT = 0;
How to configure
Section titled How to configure{ "linter": { "rules": { "correctness": { "noInvalidUseBeforeDeclaration": "error" } } }}