archives

« Bugzilla Issues Index

#3009 — typeof on TDZ variable


typeof x; // "undefined"

{
// TDZ
typeof x; // ReferenceError
let x = 42;
}

Not debating TDZ semantics here.

But I think since `typeof` has the special case that it doesn't throw an error on undeclared variables, it would be good for consistency if `typeof` on a variable in its TDZ was also error-safe, and just also returned "undefined".


You can take this up on esdiscuss if you want to get other opinions, but I don't agree.

In you example 'x' isn't undeclared, it's uninitialized. The TDZ is designed to find errors like this. Why would you want to hide them.

Type legacy typeof behavior presumably goes back to the days when it was considered ok to create global variable simply by assigning to an undeclared named. From that perspective you could consider all possible names to preexist as global variables with the value undefined.


(In reply to comment #1)
> In you example 'x' isn't undeclared, it's uninitialized.

I never claimed that the `x` in the block was undeclared. But it is unusable (without an error) at that point in a very similar way to how undeclared variables are unusable.

I (and many others) have always considered it a useful feature of `typeof` that you can "safely" (without an error) check if a variable can be referenced. I would like the same capability with `let` declarations.

And that goes a thousand times more since the official stance from TC39 seems to be "let is the new var".



> The TDZ is designed to find errors like this. Why would you want to hide them.

I don't consider it an error anymore than the common practice of checking to see if a global has been defined -- if so, using it; if not, using some other value.

This kind of pattern has been around in JS for ages:

var y = (typeof x !== "undefined") ? x : z;

I'm suggesting that the same type of pattern could be useful for `let` declarations.



> Type legacy typeof behavior presumably goes back to the days when it was
> considered ok to create global variable simply by assigning to an undeclared
> named. From that perspective you could consider all possible names to preexist
> as global variables with the value undefined.

I'm not sure if that's where this exception to `typeof` comes from historically, but it's not at all the motivating scenario for my issue report (see above).

I most definitely don't want to assign to variables to implicitly declare them. I (like almost everyone else) explicitly warn to do the exact opposite.


closing

I don't think you are going to find any T39 interest in this proposal