Yes, if you do not specifically use the let
keyword in a for
, for...of
or for...in
loops etc, they will work the same as when you use the let
keyword.
However, when you don't explicitly declare using let
keyword, the variable will be declared as a var
. let
and const
are block level variables, but you also need to understand that 'functions are not the only blocks, any { }
is basically a block'. i.e. Once declared a 'var' will become a function scoped variable and in case it is not inside a function, and declared outside, then it becomes globally available, which is not such a good thing considering you might have multiple for loops using a variable named 'i' and if you don't use let, it will just keep incrementing the old 'i'
. Please see the below two examples to understand what I mean by the above sentence:
const test = function(){
let let1 = 1;
var var1 = 2;
{
let let1 = 9; //This is a block scoped variable limited to this { } block
var var1 = 3; //re-initialization still overrides the original var 1 variable's value because once declared, the var variable is function scoped
console.log(let1); //9 - Block Scoped
console.log(var1); //3 - Function Scoped
}
console.log(let1); //1 - Function Scoped
console.log(var1); //3 - Still Function Scoped, always function scoped
}
test();
What I meant by globally incrementing value of 'i'
:
for(i=0; i< 2; i++){
console.log('first loop', i)
}
for(i;i< 5; i++){//I am not initializing i to 0, but I'm just trying to show that it is a global variable now.
console.log('second loop', i)
}
for(i; i< 7; i++){ //I am not initializing i to 0, but I'm just trying to show that it is a global variable now.
console.log('third loop', i)
}
Secondly, in ES5, Strict Mode was introduced, which basically is a way you can opt out of writing 'sloppy mode' JS code, and you can use it by specifying 'use strict';
globally or at a function level. And strict mode is used in most companies and developers in their professional code bases.
The point I want to convey with this is that 'Strict Mode' does not allow you to use for loops without declaring the variable, you have to explicitely specify the 'var' or 'let' keywords. Therefore it is always a good practice to declare your variables. You can read more about strict mode here: Strict Mode
Lastly, in the current post ES6 times, using the var
keyword to declare variable is not considered as a good practice due to something called as Hoisting, which basically means that before the a var x;
is declared, if you try to use it, you still can, however it's value will be 'undefined'. But in case of let
you cannot use a variable before you declare it. You can read more about it Here : Hoisting
Also, in case of let
if you try to access a variable before it's initialized, it throws you a Reference Error. This is because of a concept called as a 'Temporal Dead Zone'. You can read more about it here: TDZ