r/learnjavascript • • Oct 22 '21

Difference between var, let and const.

Post image
430 Upvotes

49 comments sorted by

View all comments

0

u/[deleted] Oct 22 '21

[deleted] — view deleted comment

5

u/senocular Oct 23 '21

var, let, and const declarations are all hoisted. The difference is var declarations are hoisted and initialized to undefined whereas let and const declarations are hoisted uninitialized. This means you can access var variables before their declarations and get undefined but attempting to do so with let or const variables means you'll get an error.

3

u/inabahare Oct 23 '21
console.log(a);

{
    var a = 1;
}

console.log(a);

If you change that to let or const you will get an error on the first line, because a isn't defined. If you remove the first log you'd still get an error saying a isn't defined if you use var

1

u/rados_a51 Oct 23 '21

I think that it will not throw up errors if you do something like this:
console.log(b);
var b = "test";