Welcome to Node.js v20.11.0.
Type ".help" for more information.
> class Point { // By convention, class names are capitalized.
... constructor(x, y) { // Constructor function to initialize new instances.
... this.x = x; // This keyword is the new object being initialized.
... this.y = y; // Store function arguments as object properties.
... } // No return is necessary in constructor functions.
... distance() { // Method to compute distance from origin to point.
... return Math.sqrt( // Return the square root of x² + y².
... this.x * this.x + // this refers to the Point object on which
... this.y * this.y // the distance method is invoked.
... );
... }
... }
undefined
>
> let m = Point(2,2)
Uncaught TypeError: Class constructor Point cannot be invoked without 'new'
> m
Uncaught ReferenceError: m is not defined
> typeof(m)
Uncaught ReferenceError: m is not defined
> m = new Point(2,2)
Uncaught ReferenceError: Cannot access 'm' before initialization
>
> typeof(m)
Uncaught ReferenceError: m is not defined
> m = new Point(2,2)
Uncaught ReferenceError: Cannot access 'm' before initialization
> m === null
Uncaught ReferenceError: m is not defined
> let m = 10
Uncaught SyntaxError: Identifier 'm' has already been declared
> m = 10
Uncaught ReferenceError: Cannot access 'm' before initialization
>
The first time I just mistyped
let m = Point(2,2)
From there on it’s not clear to me is this variable m defined or not?
Somehow it behaves as both defined and not defined.
Could anyone explain, in what state is the variable m?
And how can we clear its state, e.g. how can we redefine ‘m’?
>Solution :
m is stuck in the Temporal Dead Zone, and will never emerge from it. It’s declared (which is why you can’t redeclare it), but not initialized (because an error occurred in the statement where it would have been initialized). As a result, it’s unusable. Note that this isn’t a situation that would occur in a non-REPL environment, because if an error were thrown during the statement where m would have been initialized, execution would exit the scope where m is declared, so you wouldn’t be stuck in this situation. It’s purely an effect of running code in the REPL.
Your options are:
- Exit the REPL and start fresh
- Use a different identifier for subsequent attempts, rather than
m - Create a different scope (for instance, by starting an anonymous block), where you can use a different
mthat isn’t stuck in the TDZ