❗accidental global variable in sloppy mode❗️
assignment to "undeclared identifier" results in "accidental global variable" / "ReferenceError"❗️
JS ⟩ concepts ⟩ sloppy mode ⟩ accidental global variable
assignment (=) to undeclared identifier in sloppy mode will result in
unlike global var, these accidental global object property can be deleted by delete❗
assignment (=) to undeclared identifier in strict mode will result in
replit:accidental global var
// '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
Was this helpful?