4

I noticed the other day that ESLint lets me use undefined variables. Here's a simple example:

import React from 'react';

export default class test extends React.Component {
    render(){
        var a = b;
        var b = 1;
        return <h1>{a}</h1>
    }
}

Visual Studio Code with ESLint plugin does not draw a red line under that first 'b'. When compiled with webpack, there are no eslint errors. When running in the browser, the console doesn't even log any errors. The only way I know something is wrong is nothing is being displayed on the screen.

Weirdly enough, if i remove the 'var b = 1', ESLint will give me an error saying b is undefined.

Here is my eslint config; nothing special

{
"parser":"babel-eslint",
"plugins":[
    "react"
],
"rules":{ },
"extends":["eslint:recommended", "plugin:react/recommended"]

}

What is the problem here? And how can I configure ESLint to catch errors like this in the future?

Thanks

davidx1
  • 3,525
  • 9
  • 38
  • 65

1 Answers1

5

The rule you are looking for is no-use-before-define:

This rule will warn when it encounters a reference to an identifier that has not yet been declared.

You are using the recommended configuration - in which that rule is not enabled. To use it, you will need to enable it explicitly:

{
  "parser":"babel-eslint",
  "plugins":[
    "react"
  ],
  "rules":{
    "no-use-before-define": "error"
  },
  "extends":["eslint:recommended", "plugin:react/recommended"]
}
cartant
  • 57,105
  • 17
  • 163
  • 197
  • 1
    Thanks for this. Is there any reason this wasn't in the recommended rule set? In which scenario would I might not want It? – davidx1 Jul 13 '17 at 18:33
  • I can't think of a situation in which you'd not want to know about a variable being used before its declaration. I guess the recommended rules set is best thought of as a minimum set of rules; there are many rules that are not in it that I would recommend using. – cartant Jul 13 '17 at 18:55
  • Actually, if the first use of the variable before its declaration were to be an assignment to said variable, the error would be spurious. – cartant Jul 13 '17 at 19:18