Vicky Gonsalves
Vicky Gonsalves

Reputation: 11707

ReferenceError for checking late declared variable with let?

I was reading about let keywords and went through this code block:

typeof behaves differently with Temporal Dead Zone (TDZ) variables than it does with undeclared (or declared!) variables. For example:

{
    // `a` is not declared
    if (typeof a === "undefined") {
        console.log( "cool" );
    }

    // `b` is declared, but in its TDZ
    if (typeof b === "undefined") {     // ReferenceError!
        // ..
    }

    // ..

    let b;
}

So how can one check its typeof as it will always give ReferenceError?
Do we need to use try ... catch block as an alternative to typeof?

  {
    try {
      console.log(typeof(b));
    } catch (e) {
      console.log(e);
    }
    let b;
  }

Upvotes: 0

Views: 73

Answers (3)

Jai
Jai

Reputation: 74738

From the docs:

In ECMAScript 2015, let will hoist the variable to the top of the block. However, referencing the variable in the block before the variable declaration results in a ReferenceError.The variable is in a "temporal dead zone" from the start of the block until the declaration is processed.

So in your code you are trying to access a var which is not been declared yet.

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816334

So how can one check its typeof as it will always give ReferenceError?

You can't. Accessing variables before they are declared is a programming mistake.

Upvotes: 2

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

Its always best practice to declared the variable where we going to first use it or declared on the top

let b;
if (typeof b === "undefined") {     //No  ReferenceError!
    // ..
}

So,it is best way remove from TDZ.

Upvotes: 0

Related Questions