JavaScript - Strict Mode
Overview
Estimated time: 10–15 minutes
Strict mode opts into safer semantics: no implicit globals, safer this
, and more errors for silent mistakes.
Learning Objectives
- Enable strict mode at file/function scope.
- Recognize key behavior changes in strict mode.
Enabling
'use strict'; // file scope
function f(){ 'use strict'; /* function scope only */ }
Key Differences
- No implicit globals (assigning to undeclared variables throws).
this
in plain function calls isundefined
(notwindow
).- Duplicate parameter names are errors.
- Some silent failures (e.g., writing to read-only properties) throw.
Examples
'use strict';
// 1) Implicit global becomes error
// oops = 1; // ReferenceError
// 2) this is undefined in plain function calls
function who(){ return this; }
console.log(who() === undefined); // true
// 3) Duplicate params
// function bad(a, a) {} // SyntaxError