codehag / js-better-errors

Let's discuss making better errors for JavaScript
MIT License
37 stars 2 forks source link

ReferenceError for TDZ errors #10

Open getify opened 5 years ago

getify commented 5 years ago

What is the code triggering the message?

{ x = 2; let x; }

What went wrong in the code? What is the system trying to tell you?

This is a TDZ error. The system is trying to tell me that that x is in its TDZ when x = 2 is accessed, and is instead not available until let x is encountered in the scope.

What error message do you see?

Side note: Notice that SpiderMonkey's error message strangely surrounds x in a ` on one side and a ' on the other. Weird.

Which JavaScript environment produced this error?

What error message would you like to see?

SpiderMonkey's error message is pretty good, much better than v8's.

But I would have worded it differently, and I would have included the "TDZ" terminology (instead of reusing the ReferenceError type) because that helps people google for this error.

TDZError: `x` cannot be accessed before its declaration

Using "initialization" in the error message is technically accurate, but it's not very helpful to the user because they likely don't understand the nuance of the fact that a let / const have been "hoisted" for the scope but not initialized. I teach that detail in my workshops, but the vast majority of devs don't understand that.

My error message shifts attention to describing the problem accurately without an unnecessary detail to distract.

If you're going to keep ReferenceError as the error class, the message should read:

ReferenceError: `x` cannot be accessed in its TDZ before its declaration

Do you agree to license your suggested error message under an MIT-style license?

Yes