granmoe granmoe -4 years ago 100
Javascript Question

ESLint rule to prevent overriding function by creating a const of the same name (especially during assignment)

Is there an ESLint rule that can catch the following?

const foo = () => 1

const bar = () => {
const foo = foo() // 1. identifier 'foo' is set to undefined in this context 2. invoking foo() results in an error since `foo` is undefined
return foo

> bar()
> Uncaught ReferenceError: foo is not defined
at bar (<anonymous>:4:15)
at <anonymous>:1:1

In other words, I would like to get a linter error when a const is assigned its own value.

Answer Source

The closest rule that I know of for your usecase is ESLint's no-use-before-define. It will see this as using foo before const foo and it will error.

The only downside is that this rule doesn't do full code-flow analysis, so it will also error for cases like

var getFoo = () => foo;

const foo = 4;


because it still sees foo as used before const foo even though at runtime it is only used after. This may not be an issue if your codebase doesn't do this or can be fixed, but it may be annoying if you're adding the rule to an existing large codebase.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download