+ 2
why some programmers crate variable with let instead var
2 Respuestas
+ 6
What will be the output?
var num = "nothing";
if (true) {
var num = 4;
}
alert(num);
There will be "4", not "nothing". If you will try to do this with function (not "if") you will see "nothing". Why?
In javascript a new block will not create a new scope. This can be done by functions only.
So variable created in for loop will be available everywhere (in current function).
But:
let num = "nothing";
if (true) {
let num = 4;
}
alert(num);
will write "nothing" because variable created by let is available in current BLOCK only, so our if block will not change our outside variable .
+ 3
With let - you can define variables which are accessible only in the scope, where the variable is created. It is more convenient than var and it is the new standard