This is due to a really annoying JS mis-feature, JS "hoists" variables during the compilation+lexing phase, but var is initialized to undefined so variables declared this way don't throw a ReferenceError if you use them before they are declared in the code. This is a huge footgun in JS, and not what you'd expect coming from any other language AFAIK.
Here's an example source file where both variables are declared below use, but only const (or let) will throw a ReferenceError due to being uninitialized:
console.debug(`${bad} should be an uninitialized variable, but I will not throw ReferenceError due to var hoisting`);
var bad = "bad";
console.debug(`${good} is not initialized yet by const/let so this message will not print`);
const good = "good";
When running it:
$ node test.js
undefined is an undefined variable, but I will not throw ReferenceError due to var hoisting
/Users/roberthelmer/src/news-disinformation-study/test.js:4
console.debug(`${good} is not defined yet by const/let so this message will not print`);
^ReferenceError: Cannot access 'good' before initialization
at Object.<anonymous> (/Users/roberthelmer/src/news-disinformation-study/test.js:4:18)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
We could simply move this line up, but I took the liberty of making it const :)
This is due to a really annoying JS mis-feature, JS "hoists" variables during the compilation+lexing phase, but
var
is initialized toundefined
so variables declared this way don't throw aReferenceError
if you use them before they are declared in the code. This is a huge footgun in JS, and not what you'd expect coming from any other language AFAIK.Here's an example source file where both variables are declared below use, but only
const
(orlet
) will throw aReferenceError
due to being uninitialized:When running it:
We could simply move this line up, but I took the liberty of making it
const
:)