Recently I was reading you should use let instead of var, is there any particular reason for this? I didn't see an explanation
Let VS Var
What is 'let' and where do you use 'var'?
Your question is not very clear to me
Ah in JavaScript sorry
- Edited
let
-declared variables only have scope between the innermost {}
containing them; var
-declared ones are scoped to the entire function—even before the var
statement is reached.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
var
is a lot sloppier than let
. Variables can be declared with var
multiple times within the same scope, but only once with let
(and if you use let
you have to declare before you can use). So you can have
var foo;
function blablabla()
{
...
... lots of code
... some of which
... uses the global foo
... variable,
... nested control structures,
... including, buried three if()s deep,
... the line
var foo = "something";
... And suddenly that foo isn't global
... anymore and was a local
... variable all along.
}
Of course, if you wrote functions like that, then mistaking local variables for global ones is the least of your problems, but still...
So it's a case of using the right tool for the job so to speak
cluelessPHP
It always is, but there probably aren't that many jobs done by var
that wouldn't be done better by let
.
Weedpacket It's a case of finding a screwdriver for the first time and using it instead of a hamer if that makes sense
Both are used for declaration in JavaScript. But the main difference is, Let is a block scope and Var is a function scope. It means you can't use the let variable without declaration but var can be used. In the below example you will understand the difference.
Input:
console.log(x);
var x=5;
console.log(x);
Output:
undefined
5
Input:
console.log(x);
let x=5;
console.log(x);
Output:
Error