4

Concretely, this happened (node v12.22.9):

me@my-machine:~/Projects/.../my-projects$ node
Welcome to Node.js v12.22.9.
Type ".help" for more information.
> let foo = (function(){ throw new Error() })()
Uncaught Error
    at REPL1:1:30
> foo
Uncaught ReferenceError: foo is not defined
> foo = 1
Uncaught ReferenceError: foo is not defined
> let foo = 1
Uncaught SyntaxError: Identifier 'foo' has already been declared
> let bar
undefined
> bar = (function(){ throw new Error() })()
Uncaught Error
    at REPL6:1:26
> bar
undefined
> bar = 1
1
> let bar = 1
Uncaught SyntaxError: Identifier 'bar' has already been declared

If you see, I cannot:

  • Retrieve the value of foo, since it is not defined.
  • Assign a new value to foo, since it is not defined.
  • Define it again (with or without initial value), since it is already defined.

This renders the identifier foo completely unusable (until I close the console session). This, however, does not happen to bar, since I don't initialize it to an expression throwing an exception (I assign bar to an expression throwing an exception after the variable bar is defined).

Is this a bug or an expected behaviour? is there a way I can clear this behaviour (without restarting the repl) and re-use foo?

Luis Masuelli
  • 12,079
  • 10
  • 49
  • 87
  • 1
    Update your node version. This was fixed some time ago iirc. – Bergi Oct 22 '22 at 13:39
  • 2
    I can find [chrome-console-already-declared-variables-throw-undefined-reference-errors-for-l](https://stackoverflow.com/questions/41255090/chrome-console-already-declared-variables-throw-undefined-reference-errors-for-l) - this behavior has also annoyed me for ages. – ASDFGerte Oct 22 '22 at 13:47
  • …or maybe not: https://github.com/nodejs/node/issues/8309 But in Chrome devtools console, you can not redeclare lexical bindings – Bergi Oct 22 '22 at 15:58

1 Answers1

0

Declare the variable with var instead of let.

Welcome to Node.js v16.18.0.
Type ".help" for more information.
> let foo = (function(){ throw new Error() })()
Uncaught Error
    at REPL1:1:30
> foo = 1
Uncaught ReferenceError: Cannot access 'foo' before initialization

Using var:

Welcome to Node.js v16.18.0.
Type ".help" for more information.
> var foo = (function(){ throw new Error() })()
Uncaught Error
    at REPL1:1:30
> typeof(foo)
'undefined'
> foo
undefined
> foo = 1
1
Dan Nagle
  • 4,384
  • 1
  • 16
  • 28