The modern mode, "use strict"
For most of its life, JavaScript grew by addition only. New features arrived; old behaviour was left untouched. That policy had one enormous virtue — code written years ago kept running — and one real cost: every early misstep the language’s designers made was frozen in place, permanently, because fixing it might break something out there on the web.
That truce held until 2009, when ECMAScript 5 (ES5) arrived. ES5 set out to fix some of those old mistakes, not only add features — but a fix that changes how existing code behaves is a dangerous thing to turn on by default. The compromise: ship the corrections off by default, and let each script opt in with a short directive at the top — "use strict".
“use strict”
The directive is literally a string — "use strict" (or 'use strict', quotes are interchangeable). Put it as the very first statement of a script and the entire script switches to the modern, corrected rules:
"use strict";
// everything below runs the modern way
...
You can also place "use strict" at the top of a function to switch on strict mode for just that function — we’ll meet functions soon. In practice, though, people flip it on for the whole file and move on.
Trying it in the browser console
Here’s a gotcha. When you run code in the browser’s developer console, it does not use strict mode by default. So a snippet that behaves one way in your script can behave differently when you paste it into the console — occasionally giving you a misleading answer.
To force strict mode in the console, enter your code as one multi-line block with the directive on top. Press Shift+Enter to add lines without running, then Enter to run the whole thing:
'use strict'; <Shift+Enter for a newline>
// ...your code
<Enter to run>
That works in current Firefox and Chrome. If you’re stuck on something older that ignores it, there’s an ugly-but-bulletproof fallback — wrap the code in an immediately-called function, which gets its own strict scope:
(function() {
'use strict';
// ...your code here...
})()
So — should you use it?
You’d expect the answer to be a flat “always turn it on.” It’s a little more nuanced than that.
Modern JavaScript’s bigger building blocks — classes and modules (both coming later) — enable strict mode automatically. Write your code as modules, and "use strict" is already in effect; adding it by hand is redundant.
So the honest recommendation is: while you’re writing plain top-level scripts, put "use strict"; at the top. Once your code lives in classes and modules — which is where modern projects end up — you can drop it, because it’s implied.
From here on, as we introduce each language feature, we’ll point out where strict and old (“sloppy”) mode differ. Reassuringly, there aren’t many differences, and every one of them exists to make your code safer. Every example in this course assumes strict mode unless a rare case says otherwise.