JavaScriptEasy
What is 'strict mode'?
Strict mode is an opt-in, restricted variant of JavaScript (enabled with "use strict") that turns silent mistakes into errors, removes some confusing features and makes code easier for engines to optimise.
How to enable it
- Put
"use strict";at the very top of a script or function. - It is on automatically inside ES modules and class bodies, so most modern code already runs in strict mode.
What changes
- Assigning to an undeclared variable throws a
ReferenceErrorinstead of creating a global. thisisundefinedin plain function calls instead of the global object.- Writing to read-only properties throws, e.g. on a frozen object or a getter-only property.
- Deleting non-deletable properties throws.
- Duplicate parameter names are a syntax error.
withis forbidden andevalcannot add variables to the surrounding scope.- Octal literals like
012are a syntax error (0o12is fine). - Reserved words such as
let,static,implementscannot be used as variable names.
Why it matters
It catches typos and accidental globals early, makes this bugs obvious instead of silently touching window, and lets engines optimise more because fewer dynamic features are allowed.
In practice
If you write ES modules or classes, you are already in strict mode. For old-style scripts, add the directive at the top of the file.
Code example
js
1"use strict";23// 1. No accidental globals4try {5 totl = 10; // typo for `total`6} catch (e) {7 console.log(e.name, "-", e.message); // ReferenceError - totl is not defined8}910// 2. `this` is undefined in a plain call11function whoAmI() {12 return this;13}14console.log(whoAmI()); // undefined (would be the global object in sloppy mode)1516// 3. Writing to a frozen object throws instead of failing silently17const config = Object.freeze({ debug: false });18try {19 config.debug = true;20} catch (e) {21 console.log(e.name); // TypeError22}2324// 4. Getter-only properties cannot be assigned25const account = { get balance() { return 100; } };26try {27 account.balance = 500;28} catch (e) {29 console.log(e.name); // TypeError30}31console.log(account.balance); // 100
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.