diff --git a/doc/api/repl.markdown b/doc/api/repl.markdown index e9bf877e8ac06c..30b65269f5a3c3 100644 --- a/doc/api/repl.markdown +++ b/doc/api/repl.markdown @@ -86,6 +86,10 @@ The special variable `_` (underscore) contains the result of the last expression 4 ``` +*NOTE*: Explicitly assigning a value to `_` in the REPL can produce unexpected +results. Also, attempting to create `_` as a `const` variable in the REPL will +fail. + The REPL provides access to any variables in the global scope. You can expose a variable to the REPL explicitly by assigning it to the `context` object associated with each `REPLServer`. For example: diff --git a/lib/repl.js b/lib/repl.js index 7f913c0801738e..01f1f5b552430a 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -562,6 +562,12 @@ REPLServer.prototype.createContext = function() { }); }); + // Refer: https://github.com/nodejs/node/pull/3729#issuecomment-155460861 + // The REPL stores the result of the last evaluated expression in context's _. + // But, in the REPL, if _ is defined as a const, then it will break the REPL. + // So, we define _ first, so that later redefiniitions will fail. + context._ = undefined; + return context; }; diff --git a/test/parallel/test-repl.js b/test/parallel/test-repl.js index 539878a9475585..76ac9fced32ccd 100644 --- a/test/parallel/test-repl.js +++ b/test/parallel/test-repl.js @@ -94,6 +94,14 @@ function error_test() { }); send_expect([ + // Ref: https://github.com/nodejs/node/pull/3729#issuecomment-155460861 + // REPL stores the result of the last evaluated expression in _. + // This test makes sure that _ can not be redefined in REPL. + { client: client_unix, send: 'const _ = 1', + expect: /^TypeError: Identifier '_' has already been declared/ }, + // `_` should still be assignable + { client: client_unix, send: '_ = 1\n_', + expect: `1\n${prompt_unix}1\n${prompt_unix}` }, // Uncaught error throws and prints out { client: client_unix, send: 'throw new Error(\'test error\');', expect: /^Error: test error/ },