1
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 ?

sau0409
  • 103
  • 5
  • The problem is not with the `console.log(a)`, it's with `a = 10`. Try this: `a = 10; let a;` and you will get the same error. This happens because the compiler thinks the `a` in `a = 10` refers to the `a` in `let a`, that is, it thinks you try to use `a` before its declaration by `let a`. – kol Oct 03 '20 at 11:45
  • thnks! I read about tdz and it helped understanding it. – sau0409 Oct 03 '20 at 12:13

1 Answers1

0

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/

Daniel
  • 5,039
  • 2
  • 28
  • 53
  • when we use 'let a ;' does it overrides the gloabal 'a' and removes it ?? also why when 'let a;' at top initializes 'a' with 'undefined' but when hoisting is done its not initialized with undefined ? – sau0409 Oct 03 '20 at 11:40
  • let was introduced to prevent usage `a` before declaring it by `let`. – Daniel Oct 03 '20 at 11:40
  • Let was not override and remove other variables. You can see it as syntax that ensures the programmer to write well-designed code, so you will see an error when in time of declaring by let there is declared `a`. – Daniel Oct 03 '20 at 11:43
  • thanks! for answering it helped in clearing a confusion. – sau0409 Oct 03 '20 at 12:14