Google JS 编码约定 - "The var keyword must not be used"

Google JS Coding Conventions - "The var keyword must not be used"

我无法理解 this paragraph:

Declare all local variables with either const or let. Use const by default, unless a variable needs to be reassigned. The var keyword must not be used

谁能解释一下这是什么意思?为什么我不应该使用 'var' 关键字?

这些约定假设ES2015及以上版本,其中有letconst,可以用来代替var。他们说不要再使用 var,因为 letconst 语义更有用(根据这些约定 [和我个人的意见,不是那很重要]).

例如,他们说不要这样做:

function foo() {
    for (var i = 0; i < 10; ++i) {
        // Do something with i
    }
}

相反,要么这样做:

function foo() {
    let i;
    for (i = 0; i < 10; ++i) {
        // Do something with i
    }
}

或这个(但请注意,最后一个版本的性能会稍微慢一些,这通常并不重要1):

function foo() {
    for (let i = 0; i < 10; ++i) {
        // Do something with i
    }
}

同样,如果您使用的变量的值永远不会改变,请使用 const:

function getTomorrow() {
    const date = new Date();
    date.setDate(date.getDate() + 1);
    return date;
}

我们可以在那里使用 const,因为 date 的值永远不会改变(只是它所引用的对象的状态)。

如果你和我一样,当你把这些付诸实践时(我不遵循这些约定,但我确实遵循这个使用 letconst 的具体例子),如果您正在使用其他良好做法(例如保持函数较小等),您会惊讶于您使用 const 而不是 let 的频率,因为您最终会得到很多 "variables" 你永远不想改变它的价值观。


1 您可能想知道为什么

之间存在性能差异
function foo() {
    let i;
    for (i = 0; i < 10; ++i) {
        // Do something with i
    }
}

function foo() {
    for (let i = 0; i < 10; ++i) {
        // Do something with i
    }
}

原因是在第二个中,为每个循环迭代创建一个 new i 变量。我们可以看到,如果我们在循环内部创建一个闭包:

function foo1() {
    console.log("let outside the loop:");
    let i;
    for (i = 0; i < 5; ++i) {
        setTimeout(() => {
            console.log(i);
        }, 0);
    }
}
function foo2() {
    console.log("let inside the loop:");
    for (let i = 0; i < 5; ++i) {
        setTimeout(() => {
            console.log(i);
        }, 0);
    }
}

foo1();
setTimeout(foo2, 50);
.as-console-wrapper {
  max-height: 100% !important;
}

同样,性能差异几乎无关紧要(并且会随着引擎在可能的情况下更好地优化它而变得更小),而且很多时候你想要第二种形式的行为(这就是为什么它被定义为方法)。但它就在那里。