For what purpose 'no-use-before-define' warns about declared functions?

Viewed 4702

I am confused about an eslint warning from rule no-use-before-define:

This rule makes perfect sense to avoid errors caused by function expressions, such as

// Case 1:
// Incorrect code; eslint warns me for good reason:

runMe() // Error: Cannot access 'runMe' before initialization

const runMe = () => { alert('expression, not hoisted') }

However, when declaring functions, it is perfectly okay to call a function before it is defined (thanks to the JS hoisting mechanism)

// Case 2:
// Correct code; for what reason does eslint warns me about this?

runMe() // Works!

function runMe() { alert('definition, hoisted') }

Is there a reason, why eslint treats both cases the same way (i.e. does it make the script run faster/disable hoisting/has some other impact)?

And the second question: Can I configure eslint to only warn me about the first case but treat the declarative function style as valid?

1 Answers

Quoting the rule documentation page (emphasis mine):

In JavaScript, prior to ES6, variable and function declarations are hoisted to the top of a scope, so it’s possible to use identifiers before their formal declarations in code. This can be confusing and some believe it is best to always declare variables and functions before using them.

There does not appear to be a way to warn only if not hoisted. You could create a custom plugin.

Related