I have read my blog about the var and let. What I see is this.
var is a function or global scope variable depend on where it is defined.
where
let is block scope variable
So in lots of articles, I see they recommend to use let instead of var. I understand that because it eliminated the conflict of the scope of a variable.
So I want to ask where to use let and where to use var? If possible please provide any relevant link for that. If I go with recommendation than I have to use let everywhere.
What I understand is this.
let
should be used in for loop as it creates its own lexical scope.
for(let i =0;i<5;i++){
setTimeout(function(){
console.log(i);
},100);
}
So in this case because of let, we will able to print 0,1,2,3,4, but if we have used var it would have print 5 time 5.
Also, I want to know your suggestion on what should be used in function scope and global scope?
let say, I have file index.js
var first = 1; // what should be used here and why
function function1(){
var first = 1; // what should be use here and why `let or var`
var first1 = 2; // what should be use here and why `let or var`
for(let i=0;i<2;i++){
console.log(i);
}
Also, I fill let is more than a variable, I create its own lexical scope, there would be more manipulation under the hood like creating IIFE sort of thing.
What I understand is that we should use function and global scope as var
and let as only block scope? Please provide any recommended link which describes what is better where and why?
Thanks.