Strict Mode's Effect on 'this'
What you'll learn: How enabling strict mode changes the default behavior of this to prevent accidental global variable creation.
The Default Behavior Changes
In the previous lesson, you learned that this in the global context refers to the global object (like window in browsers). But when you enable strict mode with 'use strict';, JavaScript changes one critical rule: in regular function calls, this becomes undefined instead of defaulting to the global object.
This is a safety feature. Without strict mode, accidentally forgetting to use new with a constructor or calling a method as a plain function would silently create global variables — a common source of bugs.
Why This Matters
Think of strict mode as a safety guard on a power tool. The "loose" mode lets you accidentally touch dangerous parts (the global object), while strict mode blocks access and forces you to be explicit about what you're doing.
function showThis() {
console.log(this);
}
showThis(); // In non-strict mode: Window/global object
'use strict';
function showThisStrict() {
console.log(this);
}
showThisStrict(); // In strict mode: undefined
This change only affects default binding — when a function is called without any context. Other binding rules (which you'll learn soon) still work normally in strict mode.
Catching Mistakes Early
Strict mode's undefined behavior helps you catch errors immediately. If you try to access properties on this inside a function that shouldn't have context, you'll get a clear error instead of mysteriously creating global variables:
'use strict';
function accidentalGlobal() {
this.oops = 'mistake'; // TypeError: Cannot set property 'oops' of undefined
}
accidentalGlobal();
Key Takeaway: Strict mode sets this to undefined in plain function calls instead of defaulting to the global object, catching bugs early and preventing accidental global pollution.