iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Strict Mode

Strict mode turns silent mistakes into thrown errors and disables some sloppy legacy behaviour. Modules and classes are strict by default; for plain scripts you opt in.

How to enable it

JS
"use strict";   // first non-comment line of the file or function

// or — ES Modules and class bodies are ALWAYS strict
// <script type="module"> … </script>

What changes

Sloppy codeIn strict mode
Assigning to an undeclared variable creates a globalThrows ReferenceError
Duplicate function parameters allowedSyntaxError
Plain this in a function is windowIt's undefined
Octal literals like 0777 allowedUse 0o777 instead
Deleting variables / functions allowedSyntaxError
with statement allowedBanned
Writing to read-only properties silently failsThrows TypeError

The classic error strict catches

JS
"use strict";
function init() {
  mispelled = 42;   // ReferenceError — caught immediately
}
init();
Tip: If you're writing modern JS (modules, classes, frameworks), you're already in strict mode. Old global scripts are the only place to remember the "use strict" directive.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Strict Mode!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Opt this script into strict mode.

' strict'; /* rest of file */

Test yourself

Q1. Enable strict mode in a script with…
Q2. ES Modules and class bodies are…
Q3. Strict mode plain `function fn() { return this; }` returns…

Discussion

Loading…