Let and Var
What is the difference between Let and Var? Please say it in an understandable way, not something you copied from the internet.
The easiest way to describe it is to try out these code:
console.log(a);
var a = 5;
console.log(a);
let a = 5;
As you can see, var
actually hoists it:
var a;
console.log(a);
a = 5;
while let
, later added to fix this bug is more intuitive, and would throw an error instead.
Always use let unless u boomer
btw for var
, you can use blocks too:
(function () {
var a = 5;
})();
console.log(a);
frick
let
is limited, while var
is global. Meaning, var
has no limit, it can be used anywhere, while let
is limited.
What are let's [email protected]
Why do we use let than?
@WilliamXing let
is different to var
in that it does not create a property on the global object (window
in a browser) when used in global scope. It also respects scope, unlike var which is scoped to the function. This can help prevent pollution.
@WilliamXing meaning like, you can't use them as far as var
Simply speaking. let
is like the "new" version of var
. The big difference is how they are scoped, let
is block scoped whereas var
is function scoped.
This stackoverflow question will give you much more info. Specifically the first answer
let
andvar
declare variables in different ways.You can't hoist variables when declaring with
let
(you can't use them before they are declared), but you can do that withvar
. Also,let
andvar
are scoped differently. If you have used functions before, you have gone into a different "scope". Scope refers to the accessibility of variables and other information stored.It's a bit confusing to me too, but
let
is refrained to the code block it is in, whilevar
is refrained to the function it is defined in. An example is that you can't use variables declared withlet
outside of the object it is defined in whilevar
can be used anywhere inside the current function it is in (think difference between functions and objects).Another difference is that you can re-declare variables declared with
var
, but not withlet
.vs
Read more: https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var