0

Is there an eslint rule to enforce that variables are declared at the top of the block? The vars-on-top rule seems to literally only apply to the var keyword, and is not what I want (e.g. it would disallow for (var i = 0; ...). Here is a contrived example.

Bad Code

doWork() {
    const work = this.getWork();

    if (work.isReady) { ... }

    let workResult = work.getResult();

    // ...

    return workResult;
}

Good Code

doWork() {
    const work = this.getWork();
    let workResult;

    if (work.isReady) { ... }

    workResult = work.getResult();

    // ...

    return workResult;
}
Josh M.
  • 26,437
  • 24
  • 119
  • 200
  • Why do you call that good code? Shouldn't `let workResult` be declared before `this.getWork()`? – Bergi Sep 20 '18 at 20:12
  • `this.getWork()` is not declared in my example, it's only called. – Josh M. Sep 21 '18 at 11:43
  • Yes, I mean it should be declared before anything else is called. `var work, workResult; work = this.getWork(); …` – Bergi Sep 21 '18 at 12:04

1 Answers1

4

I'm unaware of a rule for that.

The var rule served a pretty important purpose: to prevent you accidentally introducing bugs due to the non-obvious hoisting behavior that vars have. The rule forced you to hoist them yourselves, making the behavior obvious (if still someone annoying)

With let and const that's no longer an issue, so the main practical reasons for enforcing that behavior aren't around any more. Using a variable before it's defined can still be a problem, but there's a no-use-before-define rule which handles that (including for let and const).

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
  • 1
    +1. In fact, it might be impossible to manually "hoist" a `const` declaration out of the control flow - it must be declared where it is initialised. – Bergi Sep 20 '18 at 20:11
  • Thanks for the response. Yes, I understand the reason for the `vars-on-top` rule and how `let`/`const` solve the issue of hoisting. This is more of a code-style issue. – Josh M. Sep 21 '18 at 11:45
  • 1
    @JoshM. Var-on-top is a horrible code style that leads to lots of duplication. Declare your variables where you need them :-) – Bergi Sep 21 '18 at 12:05
  • @Bergi I know it's subjective but if you are declaring variables in the middle of a function, your function probably is too long and should be split out. – Josh M. Sep 21 '18 at 16:07