question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

prefer-const detect unnecessary let

See original GitHub issue

Please describe what the rule should do: Detect uses of let where reassignments and accesses happen only in the same function, Eg not in a nested function or loop.

If a variable is only reassigned and accessed inside one function, then the value must have stabilized by the point of the function’s return, therefore it can always be replaced with a const. (While this also applies to loops, the developer would have to switch to using reduce or recursion)

What category of rule is this? (place an “X” next to just one item)

[ x] Enforces code style [ ] Warns about a potential error [x ] Suggests an alternate way of doing something [ ] Other (please specify:)

Provide 2-3 code examples that this rule will warn about:

// bad
function foo() {
  let itWorks = false;
  try {
    checkIfItWorks();
    // only mutated/accessed inside function foo
    itWorks = true;
  } catch {
    // only mutated/accessed inside function foo
    itWorks = false;
  }
  ...
}

// good
function foo() {
  const itWorks = (() => 
    try {
      checkIfItWorks();
      return true;
    } catch {
      return false;
    }
  })();
   ...
}

// bad
function foo() {
  let result = getResult();
  if (!result) {
    // only mutated/accessed inside function foo
    result = getDefaultResult();
  }

  ...;
}

// good
function foo() {
  const result = getResult() || getDefaultResult();
  ...;
}

// good
function urlUpdater() {
  let innerUrl = 'https://example.com';
  const DEFAULT = Symbol('DEFAULT');
  return function getOrUpdate(newUrl = DEFAULT) {
    if (newUrl === DEFAULT) {
        return innerUrl;
    }
    // defined in function foo and mutated in getOrUpdate
    innerUrl = newUrl;
  }
}

// 'good'
function isPromiseZalgo() {
  let canary = true;
  // canary accessed in arrow. Changes behavior if using https://github.com/krakenjs/zalgo-promise
  const isZalgoProm = Promise.resolve().then(v => canary);
  canary = false;
  return isZalgoProm;
}

// 'good'
function countIf(vals, fn) {
    let count = 0;
    for (const val of vals) {
      if fn(vals) {
        // defined in countIf, mutated in nested for loop.
        count = count + 1;
      }
    }
}

Why should this rule be included in ESLint (instead of a plugin)? Would be a sensible enough to add an option to prefer const.

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:3
  • Comments:16 (16 by maintainers)

github_iconTop GitHub Comments

1reaction
graingertcommented, Oct 12, 2017

I’m not suggesting an autofixer, I think that would be out of scope. In terms of what I’d prefer for your example, I’d go for:

const mod = shouldAddTwo() ? 0 : 2;
const foo = 1 + mod;
const bar = 2 + mod;
1reaction
not-an-aardvarkcommented, Oct 12, 2017

Could you clarify what the rule would do in cases like this?

let foo;
let bar;

if (condition()) {
  foo = 1;
  bar = 2;
} else {
  foo = 3;
  bar = 4;
}

At the moment I don’t think this preference is common enough to be worth adding to ESLint core, but I’m open to being convinced otherwise. (Of course, you could always enforce this preference yourself by implementing it as a rule in a plugin.)

Read more comments on GitHub >

github_iconTop Results From Across the Web

prefer-const - ESLint - Pluggable JavaScript Linter
A pluggable and configurable linter tool for identifying and reporting on patterns in JavaScript. Maintain your code quality with ease.
Read more >
'number' is never reassigned. Use 'const' instead. (prefer- ...
If a variable is never modified, using the const declaration is better. Const declaration tells readers, “this variable is never modified,” ...
Read more >
prefer-as-const | typescript-eslint
This rule reports when an as with an explicit literal type can be replaced with an as const .
Read more >
prefer-const - Rule
Rule: prefer-const​​ Requires that variable declarations use const instead of let and var if possible.
Read more >
Airbnb JavaScript Style Guide()
const and let only exist in the blocks they are defined in. ... 3.8 Prefer the object spread operator over Object.assign to shallow-copy...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found