deno.com

优先使用 const

注意:此规则是推荐规则集的一部分。
deno.json 中启用完整集合
{
  "lint": {
    "rules": {
      "tags": ["recommended"]
    }
  }
}
使用 Deno CLI 启用完整集合
deno lint --rules-tags=recommended
通过将其添加到deno.json中的includeexclude数组,可以将此规则明确地包含或排除在当前标签的规则集中。
{
  "lint": {
    "rules": {
      "include": ["prefer-const"],
      "exclude": ["prefer-const"]
    }
  }
}

建议使用const而非let来声明变量。

自 ES2015 起,JavaScript 支持使用letconst声明变量。如果变量用let声明,则它们是可变的;我们可以在之后为其设置其他值。同时,如果用const声明,则它们是不可变的;我们无法对其进行重新赋值。

通常,为了使代码库更健壮、更易于维护和更具可读性,强烈建议尽可能使用const而不是let。可变变量越少,在阅读代码时就越容易跟踪变量状态,因此编写出有缺陷代码的可能性就越小。因此,此 lint 规则会检查是否存在本可以声明为const而非let的变量。

请注意,此规则不检查var变量。相反,no-var 规则负责检测和警告var变量。

无效示例

let a = 0;

let b = 0;
someOperation(b);

// `const` could be used instead
for (let c in someObject) {}

// `const` could be used instead
for (let d of someArray) {}

// variable that is uninitialized at first and then assigned in the same scope is NOT allowed
// because we could simply write it like `const e = 2;` instead
let e;
e = 2;

有效示例

// uninitialized variable is allowed
let a;

let b = 0;
b += 1;

let c = 0;
c = 1;

// variable that is uninitialized at first and then assigned in the same scope _two or more times_ is allowed
// because we cannot represent it with `const`
let d;
d = 2;
d = 3;

const e = 0;

// `f` is mutated through `f++`
for (let f = 0; f < someArray.length; f++) {}

// variable that is initialized (or assigned) in another scope is allowed
let g;
function func1() {
  g = 42;
}

// conditionally initialized variable is allowed
let h;
if (trueOrFalse) {
  h = 0;
}

您找到所需内容了吗?

隐私政策