When should I use let and var?

callumacrae picture callumacrae · Feb 20, 2014 · Viewed 26.5k times · Source

EDIT: Please read the question! I already know the difference. This is not a duplicate.

Obviously, right now I should always be using the var key word as let isn't supported in everything.

When the let keyword has better support (say, I'm writing a Node application in a couple years time which uses Harmony), when should I use the let keyword vs the var keyword?

I understand the difference —var is for function scoping while let is for block scoping—but I'm looking for something like "always use the let keyword" or "use the var keyword at the top of functions, but the let keyword in blocks like for loops".

Answer

neelsg picture neelsg · Feb 20, 2014

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:

  1. Less risk of overriding some global variable use for something else
  2. Less risk of memory leaks due to variables staying in memory long after they have become irrelevant