What's the difference between using “let” and “var” to declare a variable in JavaScript?
Posted Chuck Lu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了What's the difference between using “let” and “var” to declare a variable in JavaScript?相关的知识,希望对你有一定的参考价值。
答案1
The difference is scoping. var
is scoped to the nearest function block and let
is scoped to the nearest enclosing block, which can be smaller than a function block. Both are global if outside any block.
Also, variables declared with let
are not accessible before they are declared in their enclosing block. As seen in the demo, this will throw a ReferenceError exception.
var html = ‘‘; write(‘#### global #### ‘); write(‘globalVar: ‘ + globalVar); //undefined, but visible try { write(‘globalLet: ‘ + globalLet); //undefined, *not* visible } catch (exception) { write(‘globalLet: exception‘); } write(‘ set variables‘); var globalVar = ‘globalVar‘; let globalLet = ‘globalLet‘; write(‘ globalVar: ‘ + globalVar); write(‘globalLet: ‘ + globalLet); function functionScoped() { write(‘ #### function ####‘); write(‘ functionVar: ‘ + functionVar); //undefined, but visible try { write(‘functionLet: ‘ + functionLet); //undefined, *not* visible } catch (exception) { write(‘functionLet: exception‘); } write(‘ set variables‘); var functionVar = ‘functionVar‘; let functionLet = ‘functionLet‘; write(‘ functionVar: ‘ + functionVar); write(‘functionLet: ‘ + functionLet); } function blockScoped() { write(‘ #### block ####‘); write(‘ blockVar: ‘ + blockVar); //undefined, but visible try { write(‘blockLet: ‘ + blockLet); //undefined, *not* visible } catch (exception) { write(‘blockLet: exception‘); } for (var blockVar = ‘blockVar‘, blockIndex = 0; blockIndex < 1; blockIndex++) { write(‘ blockVar: ‘ + blockVar); // visible here and whole function }; for (let blockLet = ‘blockLet‘, letIndex = 0; letIndex < 1; letIndex++) { write(‘blockLet: ‘ + blockLet); // visible only here }; write(‘ blockVar: ‘ + blockVar); try { write(‘blockLet: ‘ + blockLet); //undefined, *not* visible } catch (exception) { write(‘blockLet: exception‘); } } function write(line) { html += (line ? line : ‘‘) + ‘<br />‘; } functionScoped(); blockScoped(); document.getElementById(‘results‘).innerHTML = html;
Global:
They are very similar when used like this outside a function block.
let me = ‘go‘; // globally scoped
var i = ‘able‘; // globally scoped
However, global variables defined with let
will not be added as properties on the global window
object like those defined with var
.
console.log(window.me); // undefined
console.log(window.i); // ‘able‘
Function:
They are identical when used like this in a function block.
function ingWithinEstablishedParameters() {
let terOfRecommendation = ‘awesome worker!‘; //function block scoped
var sityCheerleading = ‘go!‘; //function block scoped
}
Block:
Here is the difference. let
is only visible in the for()
loop and var
is visible to the whole function.
unction 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) //and there is a separate tuce variable for each iteration of the loop } //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 }
Redeclaration:
Assuming strict mode, var
will let you re-declare the same variable in the same scope. On the other hand, let
will not:
‘use strict‘;
let me = ‘foo‘;
let me = ‘bar‘; // SyntaxError: Identifier ‘me‘ has already been declared
‘use strict‘;
var me = ‘foo‘;
var me = ‘bar‘; // No problem, `me` is replaced.
答案2
let
can also be used to avoid problems with closures. It binds fresh value rather than keeping an old reference as shown in examples below.
for(var i = 1; i < 6; i++) {
document.getElementById(‘my-element‘ + i)
.addEventListener(‘click‘, function() { alert(i) })
}
Code above demonstrates a classic javascript closure problem. Reference to the i
variable is being stored in the click handler closure, rather than the actual value of i
.
Every single click handler will refer to the same object because there’s only one counter object which holds 6 so you get six on each click.
General workaround is to wrap this in an anonymous function and pass i
as argument. Such issues can also be avoided now by using let
instead var
as shown in code below.
‘use strict‘;
for(let i = 1; i < 6; i++) {
document.getElementById(‘my-element‘ + i)
.addEventListener(‘click‘, function() { alert(i) })
}
以上是关于What's the difference between using “let” and “var” to declare a variable in JavaScript?的主要内容,如果未能解决你的问题,请参考以下文章
Only Link: What's the difference between dynamic dispatch and dynamic binding
What's the difference between @Component, @Repository & @Service annotations in Spring?(代码片段
[Spark]What's the difference between spark.sql.shuffle.partitions and spark.default.parallelism?
What's the difference between using “let” and “var” to declare a variable in JavaScript?
What’s the difference between JavaScript and ECMAScript?
[转]what’s the difference between @Component ,@Repository & @Service annotations in Spring