citp / news-disinformation-study

A research project on how web users consume, are exposed to, and share news online.
8 stars 2 forks source link

Survey id undefined when opening survey in same tab #75

Closed rhelmer closed 3 years ago

rhelmer commented 3 years ago

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 :)