How do JavaScript variables work?

后端 未结 5 2117
星月不相逢
星月不相逢 2020-12-03 11:40

I know that JavaScript vars point to a value:

var foo = true;
//... later 
foo = false;

So in that example I\'ve changed foo p

5条回答
  •  清歌不尽
    2020-12-03 11:56

    By constantly declaring var before the variable name, you could be instructing the JavaScript engine or interpreter to re-initialize the variable to an undefined value (undefined as opposed to a number, string/text, boolean value, or null) before assignment, which would be extra instructions, slowing down the speed of loop execution. You're also inflating code size and reducing the speed at which the code is parsed/interpreted/compiled.

    For virtually any application, there is no functional difference, but there still is one and the difference might be noticeable after hundreds of thousands or billions of loop executions. However, repeated VAR declarations of the same name within a function leads to fatal exceptions in Chrome / V8.

    UPDATE: Using var before the variable name is provably slower than omitting var as demonstrated by the following benchmark run on Chrome / v8 with the JavaScript console.

    var startTime = new Date().getTime();
    var myvar;
    for (var i=0; i<100000; i++){
        myvar = i;
    }
    console.log(new Date().getTime() - startTime);
    
    var startTimx = new Date().getTime();
    var myvax;
    for (var j=0; j<100000; j++){
    var myvax = j;
    }
    console.log(new Date().getTime() - startTimx);
    161
    169
    

    The first test executed in 161 ms and the second test (with var) took 169 ms to execute. That's a difference of 7 ms, consistent after multiple runs of the benchmark.

    The entire benchmark was pasted into the Chrome JavaScript console and then compiled before its execution, which is why the first output does not appear below the first call to console.log().

    Try it yourself!

提交回复
热议问题