JavaScript Strict Mode, debugger and with: What "use strict" Changes
How to turn on strict mode, why modules and classes are always strict, everything it changes (implicit globals, silent failures, this in plain calls, arguments, eval, octal literals, reserved words), plus the debugger statement and the deprecated with statement.
kvi5hnuCode Sprout team member8 min readOn this page
JavaScript was designed in ten days in 1995, and some early decisions turned out to be mistakes: assigning to a misspelled variable silently created a global, writing to a read-only property silently did nothing, and this in a plain function call was the global object. They couldn't simply be removed, because millions of pages depended on them. So ES5 (2009) introduced strict mode: an opt-in version of the language with those mistakes fixed. Code that doesn't opt in is informally called sloppy mode.
Today you mostly get strict mode without asking, but you'll still meet both, and the differences show up in interviews and in odd bugs. This article lists them all, then covers the two remaining statements of the language: debugger and with.
Turning strict mode on
Strict mode applies to a whole script or a whole function, never to a single block:
"use strict"; // first statement of a script: the whole script is strict
function legacy() {
// sloppy, if the script above didn't opt in
}
function modern() {
"use strict"; // first statement of a function: just this function
}
"use strict" is a directive: a plain string expression statement that the engine treats specially. It only counts if it comes before any other statement (comments are fine). Anywhere else, it's an ordinary, useless string:
const late = new Function('let a = 1; "use strict"; undeclaredZ = 2; return "still sloppy";');
console.log(late());
still sloppy
Code that is always strict
You don't need the directive in:
- ES modules: any file loaded with
import,<script type="module">,.mjsfiles, or"type": "module"in Node'spackage.json. - Class bodies: everything inside
class { ... }, including methods.
Since modern code is written as modules and classes, it's strict by default. Code bundled from modules usually stays strict too. Sloppy mode survives in classic <script> tags without the directive, old Node.js CommonJS files, browser consoles, new Function bodies and inline event handler attributes.
One restriction: a function with non-simple parameters (defaults, rest parameters or destructuring) can't contain its own "use strict" directive. That's a SyntaxError; make the enclosing script or module strict instead.
What strict mode changes

Here are the main differences, each run in both modes. The demo builds functions with new Function, whose bodies are sloppy unless they start with the directive, so the results don't depend on how this page's code is run:
function compare(label, body) {
const run = (code) => {
try {
const v = new Function(code)();
return v === undefined ? "ok" : String(v);
} catch (err) {
return err.name;
}
};
const strict = run('"use strict";' + body); // strict first: the sloppy run may create a global
console.log(label.padEnd(26), run(body).padEnd(15), strict);
}
console.log("".padEnd(26), "sloppy".padEnd(15), "strict");
compare("assign undeclared", "undeclaredVar = 1; return 'created global'");
compare("this in plain call", "return String((function () { return this === globalThis; })())");
compare("write frozen property", "const o = Object.freeze({ a: 1 }); o.a = 2; return o.a");
compare("set prop on primitive", "'abc'.len = 1; return 'ignored'");
compare("duplicate parameters", "return typeof function (a, a) {}");
compare("legacy octal 010", "return 010");
compare("with statement", "with (Math) { return max(1, 5); }");
compare("var inside eval", "eval('var q = 1'); return typeof q");
compare("arguments vs param", "return (function (a) { a = 9; return arguments[0]; })(1)");
sloppy strict
assign undeclared created global ReferenceError
this in plain call true false
write frozen property 1 TypeError
set prop on primitive ignored TypeError
duplicate parameters function SyntaxError
legacy octal 010 8 SyntaxError
with statement 5 SyntaxError
var inside eval number undefined
arguments vs param 9 1
Going through them:
- No implicit globals. Assigning to an undeclared name throws a
ReferenceErrorinstead of creating a global variable (article 20). This alone catches countless typos:totl = total + 1fails loudly. thisisn't replaced by the global object. In a function called without an object (f()),thisisundefinedinstead ofglobalThis. Forgettingnewor losing a method'sthis(article 29) then fails immediately with a TypeError instead of quietly reading and writing global properties. Likewise,f.call(null)givesthis === nullrather than the global object, andf.call(5)gives the number 5 rather than aNumberwrapper object (part 8).- Silent failures become errors. Writing to a read-only or getter-only property, adding properties to a frozen or non-extensible object, deleting a non-configurable property (article 37), or setting a property on a primitive all throw
TypeErrors. - Duplicate parameter names are a SyntaxError.
- Legacy octal literals like
010and octal escapes like"\101"are SyntaxErrors. Write0o10(article 6). withis forbidden (see below).evalcan't create variables in the calling scope (article 36), andevalandargumentscan't be used as names or assigned to.argumentsno longer mirrors parameters. Changing a parameter doesn't changearguments[i], and vice versa.arguments.calleethrows.deleteof a plain variable name is a SyntaxError (article 37).- More reserved words:
implements,interface,let,package,private,protected,public,staticandyieldcan't be identifiers (article 6). - Functions declared in blocks are block-scoped (article 38).
Strict mode also enables some engine optimizations, since code that can't create variables through eval or with is easier to analyze.
The debugger statement
debugger; is a breakpoint written in code. When developer tools are open (browser DevTools, or Node with --inspect and a debugger attached), execution pauses at that line, and you can inspect variables, the call stack and step through the code. When no debugger is attached, it does nothing:
function applyDiscount(cart) {
const total = sumItems(cart);
debugger; // pauses here only when DevTools is open
return total * 0.9;
}
It's handy for code that's hard to reach with a click-to-set breakpoint, such as code generated at run time or a line deep inside a bundle. Remove it before committing: ESLint's no-debugger rule (in the recommended set) reports it, and most production builds strip it.
The with statement (don't use it)
with (object) statement adds an object's properties to the scope chain, so inside the statement, names are looked up on the object first:
const sloppyWith = new Function(`
const config = { host: "example.com", port: 443 };
with (config) {
return host + ":" + port;
}
`);
console.log(sloppyWith());
example.com:443
It looks convenient, but neither readers nor the engine can tell, from the code alone, whether a name refers to a property of the object or to a variable outside. If config happened not to have a port property, port would silently refer to an outer variable, or create a global when assigned. That's why with is forbidden in strict mode and therefore in all modules and classes, and slow where it still works. Use destructuring instead (article 28):
const { host, port } = config;
const address = `${host}:${port}`;
Statements at a glance
That completes JavaScript's statements. A summary of Part 5:
| Statement | Purpose | Article |
|---|---|---|
expression statement, { }, ; | side effects, grouping, nothing | 38 |
let, const, var, function, class, import, export | declarations | 25–28, 38 |
if/else, switch | conditionals | 39, 40 |
while, do/while, for | condition-based loops | 41 |
for...of, for await...of, for...in | iteration | 42 |
break, continue, labels, return, yield | jumps | 43 |
throw, try/catch/finally | exceptions | 44 |
"use strict", debugger, with | mode, debugging, legacy | 45 |
Common questions
Do I need to write "use strict" in modern code?
Not in ES modules or class bodies, which are always strict. You only need it in classic scripts and CommonJS files that aren't processed by a tool that adds it. TypeScript's alwaysStrict option (on under strict) emits it for non-module files.
Is strict mode slower?
No. If anything, strict code is easier to optimize, since engines don't have to account for with, scope-changing eval or the arguments-parameter link.
Can I turn strict mode off inside a strict file?
No. Once a script, module or function is strict, everything nested inside it is strict too. The only way to get sloppy code from strict code is to create it from a string, with new Function or an indirect eval, which is almost never a good idea.
Why is this in a plain function undefined in strict mode but the global object in the browser console?
The console runs sloppy code by default, so this there falls back to the global object. Paste the same function into a module or add "use strict", and this is undefined.
Summary
- Strict mode is enabled by a
"use strict"directive at the top of a script or function, and is always on in modules and class bodies. - It turns silent failures into errors: implicit globals throw
ReferenceError, writes to read-only properties and primitives throwTypeError. thisin a plain function call isundefined, not the global object.- It forbids
with, duplicate parameters, legacy octal literals,deleteof variables and several reserved words, and stopsevalfrom creating variables in the caller. debugger;pauses execution when developer tools are attached; remove it before shipping.withmakes name lookup ambiguous; use destructuring instead.
Practice Questions
In a classic (sloppy) script, this function contains a typo. What happens in sloppy mode, and in strict mode?
function setup() {
conter = 0;
}
Answer
Sloppy: calling setup() silently creates a global variable conter, and the intended variable is never set. Strict: setup() throws a ReferenceError: conter is not defined, pointing straight at the typo.
Is this file strict?
// app.js\n"use strict";
\nimport { x } from "./lib.js";
Answer
Yes, twice over: it uses import, so it must be loaded as a module, and modules are always strict. The directive is harmless but unnecessary.
Why does this code behave differently in the two modes?
function Point(x) {
this.x = x;
}
const p = Point(3);
Answer
It's called without new. In sloppy mode, this is the global object, so it silently creates a global x and p is undefined. In strict mode, this is undefined, so this.x = x throws a TypeError immediately.
What's wrong with this code?
function f(a = 1) {
"use strict";
}
Answer
A function with non-simple parameters (here a default value) can't have its own "use strict" directive; it's a SyntaxError. Put the directive at the top of the script, or use a module.
Review quiz
You've finished Part 5. Check your understanding with the Statements review quiz: 25 questions on blocks and empty statements, if/else, switch, every kind of loop, break, continue and labels, exceptions and finally, and strict mode.
Previous: JavaScript Exceptions: throw, try/catch/finally, Error Types and Error Handling Patterns
Next: JavaScript Objects: Creating Objects with Literals, new and Object.create

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.