When should I use let and var? [closed]
I would say that you should, as a principle, use let
whenever it is not inconvenient to do so. Such as:
for (let i = 0; i < 100; i++) { // Do something}if (condition) { let msg = a + b + c; console.log(msg); alert(msg);}
The advantages to this approach is:
- Less risk of overriding some global variable use for something else
- Less risk of memory leaks due to variables staying in memory long after they have become irrelevant
Use let as a general rule, and var on occasion.
Block scoping is the standard and most readable choice, and will make debugging easier. Block scoping makes it easy to see exactly where a variable is in scope. Function scoping makes things a lot less apparent, and much easier to accidentally introduce bugs with scoping mistakes.
In general, the smaller the scope you can use, the better. Thus let
over var
.
In particular, it helps deal with the endless problem of closing over variables and not realising their value will change before the closure is executed:
for (var i = 1; i <= 5; i++) { var item = document.createElement("LI"); item.appendChild(document.createTextNode("Item " + i)); let j = i; item.onclick = function (ev) { alert("Item " + j + " is clicked."); }; list.appendChild(item);}
Well the answer is quite simple use var
if you need function scoping and let
if you need block scoping.