0

I just wonder how variable hoisting in NodeJS works. In the example below

console.log(name);
var name = "Rambou";

execution returns undefined which is correct since Hoisting works. var name; is being moved to the top like

var name;
console.log(name);
name = 'Rambou';

The question is: Why hoisting does not work for let and const? Both examples below return exception of an undefined variable.

console.log(name);
let name = "Rambou";
console.log(name);
const name = "Rambou";

ReferenceError: name is not defined

at evalmachine.<anonymous>:1:13
at Script.runInContext (vm.js:133:20)
at Object.runInContext (vm.js:311:6)
at evaluate (/run_dir/repl.js:133:14)
at ReadStream.<anonymous> (/run_dir/repl.js:116:5)
at ReadStream.emit (events.js:198:13)
at addChunk (_stream_readable.js:288:12)
at readableAddChunk (_stream_readable.js:269:11)
at ReadStream.Readable.push (_stream_readable.js:224:10)
at lazyFs.read (internal/fs/streams.js:181:12)

Execution has happened at repl.it platform.

Rambou
  • 968
  • 9
  • 22
  • @HassanImam could you provide a link of the javascript specification where I can read more about it? Are you referencing in ES5, ES6 or other? – Rambou Sep 24 '19 at 17:45
  • 2
    `let` and `const` declarations remain uninitialized. However I believe technically they are hoisted. Check [this out](https://blog.bitsrc.io/hoisting-in-modern-javascript-let-const-and-var-b290405adfda) – silencedogood Sep 24 '19 at 17:47
  • Tagged question contains good explanation as well as good reference, do check out that. – Hassan Imam Sep 24 '19 at 17:47
  • @HassanImam you comment is wrong. `let` and `const` **are** hoisted [13.3.1Let and Const Declarations](https://www.ecma-international.org/ecma-262/6.0/#sec-let-and-const-declarations) `[...]The variables are created when their containing Lexical Environment is instantiated but may not be accessed in any way until the variable’s LexicalBinding is evaluated[...]`. And as it is hoisted, this code: `let test = 4; function foo() {console.log(test); let test=5;} foo();` results in a ReferenceError. – t.niese Sep 24 '19 at 17:56
  • I agree that the comment is wrong, all the variables and functions are hoisted but accessing the variables created with `let` and `const` in the `temporal dead zone` result in `ReferenceError`. – Hassan Imam Sep 25 '19 at 06:05

0 Answers0