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 code | In strict mode |
|---|---|
| Assigning to an undeclared variable creates a global | Throws ReferenceError |
| Duplicate function parameters allowed | SyntaxError |
Plain this in a function is window | It's undefined |
Octal literals like 0777 allowed | Use 0o777 instead |
| Deleting variables / functions allowed | SyntaxError |
with statement allowed | Banned |
| Writing to read-only properties silently fails | Throws 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 */
Three letters.
Discussion
Loading…