a= 10; console.log(a); let a; => Cannot access 'a' before initialization
above code gives error for initialization, even if a is declared before use. Please explain how this gives an error if a is already hoisted and get declared "a=10" before using it.
That also means if a variable is declared with let or const, hoisting doesn't have any practical impact ?
if I run below code
let a; console.log(a); => undefined
in this case I am able to print a i.e. undefined, without initializing it.
What is happening in core ?
When you type:
then you are defining a global variable. It is deprecated and not recommended style of coding in almost all languages.
To prevent declaring global variables es6 introduced
letandconst.Now when you are using
letorconstyour interpreter checks that when you typingyou do not have
aused before this declaration. This is the reason for the error.Update:
You typed:
it is ok because
aisdeclared, memory is reserved, the symbolais registered, but the value is not assigned, so when you evaluate the value assigned to symbolait isundefined.Please compare it with case:
You will get an error:
because the symbol
cwas never declared.Now when you will assign values to
ait will be done in local scope, but when you will assign values tocit will create global variables.To improve your understanding please read about all methods of defining variables and look at all edge cases. A great article is under the link:
https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/