让vs var表现

Tec*_*ner 8 javascript ecmascript-6

我一直在阅读有关ES6 Let关键字与现有var关键字的内容.

我有几个问题.我理解"范围"是let和var之间的唯一区别,但它对大局意味着什么?

function allyIlliterate() {
    //tuce is *not* visible out here

    for( let tuce = 0; tuce < 5; tuce++ ) {
        //tuce is only visible in here (and in the for() parentheses)
    };

    //tuce is *not* visible out here
};

function byE40() {
    //nish *is* visible out here

    for( var nish = 0; nish < 5; nish++ ) {
        //nish is visible to the whole function
    };

    //nish *is* visible out here
};
Run Code Online (Sandbox Code Playgroud)

现在我的问题:

  1. 是否比var具有任何内存(/性能)优势?

  2. 除了浏览器支持,我应该使用let over var的原因是什么?

  3. 在我的代码工作流程中开始使用let now over var是否安全?

谢谢,R

小智 6

let比node.js中的var慢得多.版本v6.3.0无论如何.有时这是戏剧性的.如果用let替换var,下面的代码大约慢三倍:

function collatz() {
    var maxsteps = 0;
    var maxval = 0;

    var x = 1;
    var n;
    var steps;

    while (x < 1000000) {
        steps = 0;
        n = x;
        while (n > 1) {
            if (n & 1)
                n = 3*n + 1;
            else
                n = n / 2;
            steps += 1;
        }
        if (steps > maxsteps) {
            maxsteps = steps;
            maxval = x;
        }
        x += 1;
    }
    console.log(maxval + ' - ' + maxsteps + ' steps');
}

collatz();
Run Code Online (Sandbox Code Playgroud)