2

I have the following JavaScript code,

var foo = {
    company: "ABC",
    name: "John"
};

var att = "";

function test(ob, i) {
    var m = JSON.stringify(ob);
    if (i < 10) {
        att = att + m;
    }
}

test(foo, 20);

In above code, var m = JSON.stringify(ob); line is unnecessary initialisation of variable when i < 10 is not true. A better code will be to move the initialization inside the if condition.

I am not able to find a code linter that can detect such scenarios. In such cases, I want a warning that variable might not be used. Does anyone know any linting tool that can do this?

I tried

  1. ES Lint
  2. JS Lint
dnsh
  • 3,516
  • 2
  • 22
  • 47
  • That would require code flow analysis of your entire program – no, I don't think any current linter does it. – AKX May 24 '22 at 13:22
  • TypeScript _might_ pick this up, but that's rather more than just a linter. (And also, library/tool recommendation requests are unfortunately off-topic on this site) – DBS May 24 '22 at 13:26
  • @DBS IMHO this is not a library/tool recommendation request which generally has opinionated answers. I am looking to solve a specific problem. – dnsh May 24 '22 at 13:46
  • @AKX Not necessarily a code flow analysis but code blocks analysis i.e. whether an initialized variable is present in some inner code blocks but not in outer code blocks (here code blocks will be only restricted to conditions that are not using the variable itself). :) – dnsh May 24 '22 at 13:51
  • This should be easy to implement - you need to look for all IF-like blocks in AST explorer and check if the given variable exists there. The only problem I see is that it could use too much resources during plugin run but it's doable. I recommend checking how AST and eslint plugin system works. I wouldn't expect such plugin to exist as it's an edge case – TwistedOwl May 24 '22 at 13:53
  • JSLint will not do this. You can try it on [jslint.com](http://jslint.com) and see. It is purely lexical and does not do flow analysis. ESLint will do "anything" if you have enough gumption to write an extension. [Here's one tutorial selected from near hte top of my google results](https://dev.to/spukas/how-to-write-your-first-eslint-plugin-145). – ruffin May 24 '22 at 16:22
  • @dnsh You'd need code flow analysis to see whether `test` is ever called with `i < 10`... – AKX May 25 '22 at 04:55

0 Answers0