Aller au contenu

noInnerDeclarations

Ce contenu n’est pas encore disponible dans votre langue.

Diagnostic Category: lint/correctness/noInnerDeclarations

Since: v1.0.0

Sources:

Disallow function and var declarations that are accessible outside their block.

A var is accessible in the whole body of the nearest root (function, module, script, static block). To avoid confusion, they should be declared to the nearest root.

Prior to ES2015, function declarations were only allowed in the nearest root, though parsers sometimes erroneously accept them elsewhere. In ES2015, inside an ES module, a function declaration is always block-scoped.

Note that const and let declarations are block-scoped, and therefore they are not affected by this rule. Moreover, function declarations in nested blocks are allowed inside ES modules.

if (test) {
function f() {}
}
code-block.cjs:2:5 lint/correctness/noInnerDeclarations ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This function should be declared at the root of the script.

1 │ if (test) {
> 2 │ function f() {}
^^^^^^^^^^^^^^^
3 │ }
4 │

The function is accessible in the whole body of the script.
To avoid confusion, it should be declared at the root of the script.

if (test) {
var x = 1;
}
code-block.js:2:5 lint/correctness/noInnerDeclarations ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This var should be declared at the root of the module.

1 │ if (test) {
> 2 │ var x = 1;
^^^^^^^^^
3 │ }
4 │

The var is accessible in the whole body of the module.
To avoid confusion, it should be declared at the root of the module.

function f() {
if (test) {
function g() {}
}
}
code-block.cjs:3:9 lint/correctness/noInnerDeclarations ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This function should be declared at the root of the enclosing function.

1 │ function f() {
2 │ if (test) {
> 3 │ function g() {}
^^^^^^^^^^^^^^^
4 │ }
5 │ }

The function is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

function f() {
if (test) {
var x = 1;
}
}
code-block.js:3:9 lint/correctness/noInnerDeclarations ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

This var should be declared at the root of the enclosing function.

1 │ function f() {
2 │ if (test) {
> 3 │ var x = 1;
^^^^^^^^^
4 │ }
5 │ }

The var is accessible in the whole body of the enclosing function.
To avoid confusion, it should be declared at the root of the enclosing function.

// inside a module, function declarations are block-scoped and thus allowed.
if (test) {
function f() {}
}
export {}
function f() { }
function f() {
function g() {}
}
function f() {
var x = 1;
}
function f() {
if (test) {
const g = function() {};
}
}