r/javascript • • Feb 23 '17

What's the difference between using "let" and "var" to declare a variable? 👍

http://stackoverflow.com/a/11444416
0 Upvotes

9 comments sorted by

3

u/from-nibly Feb 23 '17

Never use var. There is not a good reason to.

1

u/tunnckoCore node-formidable, regexhq, jest, standard-release Feb 24 '17

that's the diff

{
  let ok = 1
  console.log(ok) // => 1
}
console.log(ok) // => Throws an error

1

u/HitlerDidNthingWrng Feb 23 '17

Block scoping.

Basically, var is scoped only to functions.

let is scoped to anytime you see these {}, which includes a for loop, while loop, etc.

const is the same as let in terms of scoping, only it can't be changed once you declare.

Also, neither can be declared more than once within the same scope, but you can do that with var.

Tip: always use const unless you plan on changing the variable. So, default to const, not let.

3

u/our_best_friend if (document.all || document.layers) console.log("i remember..") Feb 23 '17

Downvoted for the username

1

u/HitlerDidNthingWrng Feb 23 '17

let thingsHitlerDidWrong = [];

1

u/magenta_placenta Feb 23 '17

Also, let is not hoisted, var is hoisted.

1

u/senocular Feb 23 '17

let is hoisted. You're just not allowed to use it prior to its declaration.

1

u/magenta_placenta Feb 23 '17

Temporal Dead Zone.

-2

u/our_best_friend if (document.all || document.layers) console.log("i remember..") Feb 23 '17

I don't understand the point of posting a SO answer for something so basic.

Also, the answer doesn't mention the difference in hoisting

 function x() {
   console.log(aaa); <-- aaa doesn't exist yet, but it's hoisted
   var aaa=1;
 };
x();
// undefined


 function x() {
   console.log(aaa); <-- aaa doesn't exist yet, fatal error
   let aaa=1;
 };
x();
// Uncaught ReferenceError: aaa is not defined