no-var

Try in Playground
javascript-best-practicesBest PracticeInformational

0

No tags

No CWE or CVE

In ECMAScript 2015, the keywords "let" and "const" was introduced for block-scope variable declaration.

Variables declared with "const" are read-only and cannot be reassigned. Using "let" instead of "var" can help prevent confusion and issues related to variable scope.

While these new keywords provide more precise variable types, they may require some refactoring and may cause syntax errors in older environments.

It is recommended to use "let" or "const" instead of "var" in environments that support ECMAScript 2015.

Ast Rule: variable declaration


no-var

How to write a rule
function visit(node, filename, code) {
  if (!node || !node.modifier || !node.modifier.value) return;

  if (node.modifier.value === "var") {
    const error = buildError(
      node.modifier.start.line,
      node.modifier.start.col,
      node.modifier.end.line,
      node.modifier.end.col,
      `Unexpected var, use let or const instead`,
      "INFORMATIONAL",
      "BEST_PRACTICE"
    );

    const letEdit = buildEditUpdate(
      node.modifier.start.line,
      node.modifier.start.col,
      node.modifier.end.line,
      node.modifier.end.col,
      "let"
    );

    const constEdit = buildEditUpdate(
      node.modifier.start.line,
      node.modifier.start.col,
      node.modifier.end.line,
      node.modifier.end.col,
      "const"
    );

    const letFix = buildFix("replace with let", [letEdit]);
    const constFix = buildFix("replace with const", [constEdit]);

    addError(error.addFix(letFix).addFix(constFix));
  }
}

var-usage.js

Expected test result: has error

A file that uses `var`

var color = "blue";
var size = 4;

let-const-usage.js

Expected test result: no error

A file that only uses `let` or `const`

const color = "blue";
let size = 4;
Add comment

Log in to add a comment


    Be the first one to leave a comment!

Codiga Logo
Codiga Hub
  • Rulesets
  • Playground
  • Snippets
  • Cookbooks
soc-2 icon

We are SOC-2 Compliance Certified

G2 high performer medal

Codiga – All rights reserved 2022.