nzim
nzim

Reputation: 165

Hoisting of let, const with separate initialization

In Documentaion said that let and const are hoisted.

Variables declared with let and const are also hoisted but, unlike var, are not initialized with a default value. An exception will be thrown if a variable declared with let or const is read before it is initialized.

Also there are a pretty clear sample there:

 console.log(num); // Throws ReferenceError exception as the variable value is uninitialized
 let num = 6; // Initialization

But I don't understand why this rise the ReferenceError also:

x = 9

console.log(x) // Why: "Throws ReferenceError exception as the variable value is uninitialized" here ?

let x;

Specs says 'let' supports hoising. Initialization is going before using this variable. What's wrong? If the reason of the ReferenceError is TDZ then why in specs says that 'let' supports hoising, becouse of TDZ and hoising are mutually exclusive things... And what could be an example of hoising for 'let' if I can't use this varibable before declaration...

Upvotes: 3

Views: 586

Answers (1)

Bergi
Bergi

Reputation: 665594

Why throws ReferenceError exception as the variable value is uninitialized here, in the console.log line?

It doesn't. It throws it on access of the variable, which includes assignment:

x = 9; // exception happens here already!
let x;

You cannot use an uninitialised variable at all. It only gets initialised when the let/const statement itself is evaluated.

What could be an example of hoisting for 'let' if I can't use this variable before declaration?

You cannot use it, but you can refer to it, e.g. by creating a closure over it:

function log() {
    console.log(x);
}
// log(); - would fail here
let x = 9;
log();

Also it means that referring to x will actually refer to that uninitialised variable, not some other x from an outer scope. See Are variables declared with let or const hoisted? for more.

Upvotes: 4

Related Questions