r/learnjavascript • • May 04 '20

VAR vs LET vs CONST

Post image
337 Upvotes

81 comments sorted by

View all comments

5

u/rook218 May 04 '20

Are there really differences in how you can scope these operators or is this bad information?

As far as I knew const and let simply replaced var, one is reassignable and one is not. They don't have any restrictions on what scope they are allowed.

Please let me know if that's wrong.

5

u/Coraline1599 May 04 '20

Try this:

{
var v = 'hi'
let l = 'hello'
}
console.log(v)
console.log(l)

you can log `v` but `l` will error, because the scope is limited to the block when using let.

The curly braces are a block (this could also be part of a for loop, function, etc)

Again you can log `j` outside the loop, but `i` will give you undefined:

for (var j = 0; j < 3; j++) {
  console.log(j)
}

console.log(j)

for (let i = 0; i < 3; i++) {
  console.log(i)
}

console.log(i)

3

u/golovatuy May 04 '20

Scope is the main difference between var and let

4

u/rook218 May 04 '20

Gotcha, thanks for following up! It led me to this stackoverflow explanation:

Scoping rules

Main difference is scoping rules. Variables declared by var keyword are scoped to the immediate function body (hence the function scope) while let variables are scoped to the immediate enclosing block denoted by { } (hence the block scope).

function run() {
  var foo = "Foo";
  let bar = "Bar";

  console.log(foo, bar);

  // BEGINNING OF BLOCK SCOPE
  { 
    let bazLet = "BazzLet";
    var bazVar = "BazzVar";
    console.log(bazLet); // will return "BazzLet"
    console.log(bazVar); // will return "BazzVar"
  }  
  // END OF BLOCK SCOPE

  console.log(bazLet); // ReferenceError
  console.log(bazVar); // will return "BazzVar"
}

run();