When should I use var, let or const?

@MTF , your code is much more elegant than what I wrote. Can you explain why codecademy stays away from teaching us “var” to declare variables? Everything I have seen so far in the course is “let” or “const”.

With the introduction of let and const in ES6 it would seem we no longer need var but to my mind it should be based on use case, not imperative. var and let are almost the same with one major difference. var does not define block scope in a loop body, whereas let does.

One supposes that the author is trying to get away from var entirely, and I cannot doubt many teachers are of the same mind. The one main reason for it not being deprected from the language would be backward compatibility.

In global scope, var declarations are rather moot. All variables declared without var, regardless what scope they may be declared in, will be global by default. That’s how JS treats them.

function foo() {
    bar = "I'm in global scope"
}
console.log(bar);    // I'm in global scope

Essentially, the only real declaration keyword needed in global scope is const, which is intended to preserve values or structures. let and var are, as stated, moot.

In function scope, declared variables using a keyword all take the scope in which they are declared. It won’t always be the case where we need block scope on our loops, but when we do, let is how we do that.

for (let i = 0; i < 10; i++) {
  //
}
console.log(i)
// <- Uncaught ReferenceError: i is not defined

Notice that i is not defined outside of the for block.

for (var i = 0; i < 10; i++) {
  //
}
console.log(i)
// <- 10

Sometimes we might want the variable to be accessible outside of the loop, so the above is valid. A let declaration before the loop would have the same effect of keeping the variable accessible after the loop.

let i;
for (i = 0; i < 10; i++) {
  //
}
console.log(i)
// <- 10

For the most part, we no longer need var in the purest sense, so there is no real requirement to include it in our lexicon of ES6, just so long as we understand the difference.

3 Likes

@MTF, This is an outstanding response! Thank you for the quick reply and the information. To be honest, I am not far enough along the course to completely understand what you are saying but I do get the gist. Thank you.

2 Likes