JavaScript hoisting confusion regarding let

52 views Asked by At
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 ?

1

There are 1 answers

4
Daniel On

When you type:

a=10

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 and const.

Now when you are using let or const your interpreter checks that when you typing

let a;

you do not have a used before this declaration. This is the reason for the error.


Update:

You typed:

let a; console.log(a); => undefined

it is ok because a is declared, memory is reserved, the symbol a is registered, but the value is not assigned, so when you evaluate the value assigned to symbol a it is undefined.

Please compare it with case:

console.log(c);

You will get an error:

Uncaught ReferenceError: c is not defined

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 to c 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/