accidental global variable in sloppy mode❗️

assignment to "undeclared identifier" results in "accidental global variable" / "ReferenceError"❗️

// 'use strict';        // sloppy mode

// test for run/compile time error
log('hello');            // hello (compilation is OK)

// test accidental global variable
function f() {
    
    function g() {
        // ❗ assignment to an "undeclared variable" 
        //    will result in:
        //    • an "accidental global variable" in "non-strict mode".
        //    • a "ReferenceError" in strict mode.
        neverDeclared = 123;
    }

    g();
}

f();

// accidental global variable❗
neverDeclared,                // 123
globalThis.neverDeclared,     // 123

in strict mode

'use strict';            // strict mode

console.log('hello');    // hello

// block scope
{
    neverDeclared = "Surprise";    // runtime error
    // ⛔️ ReferenceError: `neverDeclared` is not defined
}

Last updated