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
let
andconst
.Now when you are using
let
orconst
your interpreter checks that when you typingyou do not have
a
used before this declaration. This is the reason for the error.Update:
You typed:
it is ok because
a
isdeclared
, memory is reserved, the symbola
is registered, but the value is not assigned, so when you evaluate the value assigned to symbola
it isundefined
.Please compare it with case:
You will get an error:
because the symbol
c
was never declared.Now when you will assign values to
a
it will be done in local scope, but when you will assign values toc
it 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/