What happens when you assign to a variable that was never declared with var, let or const, for example total = 10; inside a function? How does strict mode change this?
Show the explanation
Model answer. In non-strict ("sloppy") code, assigning to an undeclared name creates a property on the global object (window in browsers, globalThis everywhere). It becomes an accidental global that any script can read or overwrite, which causes hard-to-trace bugs:
function addTax(price) {
total = price * 1.18; // no declaration: leaks a global called total
return total;
}In strict mode ('use strict', and automatically inside ES modules and classes), the same line throws ReferenceError: total is not defined. That turns a silent bug into an immediate error.
Note that reading an undeclared name throws in both modes; only writing differs. typeof undeclaredName is the one safe way to check, because it returns "undefined" instead of throwing.
Fix: always declare variables, and write modules (which are strict by default).
Original UniCircle question. Last reviewed 22 Oct 2026.
