cf.completefrontendCode editorOpen lab
THE JAVASCRIPT FIELD GUIDE

Strict mode

Learn how JavaScript strict mode turns silent mistakes into errors, how the "use strict" directive prologue works, and why modules and classes are strict automatically.

By the end, you can
  • 01
    Place the directive correctlyExplain why "use strict" only counts in a directive prologue.
  • 02
    Predict strict-mode errorsCompare silent sloppy behavior with strict ReferenceError, TypeError, and SyntaxError results.
  • 03
    Recognize modern defaultsKnow that ES modules and classes are strict without writing the directive yourself.

Strict mode in one sentence

Strict mode is JavaScript's modern checking mode. It keeps the language familiar, but it changes several older "I'll guess what you meant" behaviors into real errors you can see and fix.

You already know that JavaScript runs statements from top to bottom, and that small typos matter. Strict mode makes that lesson kinder: it catches more mistakes near the line where they happened instead of letting a confusing result appear later.

Real-life analogyStrict mode is a spelling checker that stops the draft

Sloppy mode is like a friend who nods along when you mispronounce a word. Strict mode is the tool that says, "Stop, that word is not in the dictionary." It feels stricter, but it saves you from carrying the typo into the rest of the program.

In real life: A typo underlined immediately
In JavaScript: An undeclared name throws ReferenceError
In real life: A locked form refuses a bad entry
In JavaScript: A read-only property throws TypeError
In real life: A style guide that applies to this document
In JavaScript: A directive prologue applies to this script or function

Where the analogy stops: A spelling checker suggests replacements. Strict mode usually just stops with an error; you still decide how to fix the code.

Definition

Strict mode is enabled for a classic script or function by putting the exact string "use strict" in its directive prologue. ES modules and class bodies are strict automatically.

This lesson compares old sloppy behavior with strict behavior, shows exactly where "use strict" has to go, and explains why the module code you will write in modern tools already gets these checks.

The "use strict" directive prologue

STEP THROUGH

"use strict" looks like a string because it is one. At the start of a script or a function, JavaScript treats certain string expression statements as directives. The consecutive directives at the very top are called the directive prologue.

Whitespace and comments may come first. Other strings may come first too. But the moment JavaScript reaches a non-string statement, the prologue is over. A later "use strict" is just an unused string expression.

Move the directive prologue
Step 0 of 3Ready
Your turn: follow the blue line

Choose where the directive appears, then step through the recorded result from a real JavaScript run.

Running in
  1. script
Next: line 1
Click the blue line to take the next stepPop out in the code editor (opens in a new tab)JavaScript
try {  typoTotal = 3;  console.log("assignment worked");} catch (error) {  console.log(error.name + ": " + error.message);}
CallStoreChangeResultRun = next line. Ran = already executed.
Recent returnsNothing yet. Start with the blue line.
Where is "use strict"?

Changing the placement starts a fresh replay.

A guided replay recorded from real JavaScript calls, not an engine debugger. Step follows executed statements; Back reviews a snapshot. Reset starts a fresh run.

The first version catches typoTotal immediately. The second version prints setup first, ignores the late string, and creates globalThis.typoTotal. Same words, different position.

Function-level strict mode

A directive can also start a function body. Only that function's code becomes strict. This helped older pages adopt strict mode one function at a time. Modern code usually chooses modules instead.

Strict or sloppy?
  • "use strict"; as the first statement in a classic script
  • console.log("hi"); before "use strict";
  • A function body that starts with "use strict";
  • An ES module file
  • A classic script with no directive
  • Code inside a class body
Try it yourself
0 of 6 correct

Sort each fragment by whether it runs in strict mode. Remember: classic scripts need a directive prologue; modules and classes do not.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

One more rule: you cannot turn strict mode off from inside strict code. A later string like "use sloppy" has no special meaning. This matters when build tools concatenate files: if a file's directive is no longer at the beginning of its new wrapper, it may stop working.

What strict mode changes

INTERACTIVE

Strict mode is not a new language. Most normal JavaScript behaves the same. The important changes are the places where old JavaScript used to silently guess, ignore, or allow confusing code.

Real-life analogyA referee who blows the whistle early

Sloppy mode lets some fouls slide and hopes the match still makes sense. Strict mode blows the whistle. That interruption is useful: you fix the foul while everyone still remembers where it happened.

In real life: The whistle stops play now
In JavaScript: An error stops the mistaken statement
In real life: The replay shows exactly where the foul happened
In JavaScript: The stack trace points near the bug
In real life: Clean play continues as usual
In JavaScript: Ordinary statements keep running the same way

Where the analogy stops: A referee can judge intent. JavaScript only follows rules: strict mode cannot tell whether a legal line is a good idea.

Toggle strict mode and run the same mistake
Sloppy versionPop out in the code editor (opens in a new tab)JavaScript
mistakeCount = 1;console.log("created global: " + ("mistakeCount" in globalThis));
Browser resultRun either version to see the real browser result.

Classic scripts are sloppy unless a directive turns strict mode on.

Try it yourself

Strict mode catches the typo instead of creating a new global name. Expected sloppy result: created global: true. Expected strict result: ReferenceError: mistakeCount is not defined.

The code runs for real in a sandboxed iframe as a classic script. The lesson validates that the message came from this iframe before showing it.
Strict mode changes you should recognize
BehaviorSloppy modeStrict mode
Undeclared assignmentCreates a global propertyThrows ReferenceError
Plain function thisBecomes the global objectStays undefined
Write to read-only dataSilently ignoredThrows TypeError
Duplicate parameter namesAllowed in old-style functionsSyntaxError before code runs
Legacy octal like 010Means eightSyntaxError; use 0o10
with statementChanges how names are looked upSyntaxError

Do not memorize every historical corner today. Remember the pattern: strict mode refuses code that creates hidden globals, hides failed writes, or makes names hard to reason about.

Mistakes strict mode refuses before running

Some strict-mode changes are syntax rules. That means JavaScript rejects the program before any line runs. You see a SyntaxError, not a logged value.

Examples that strict mode rejectsPop out in the code editor (opens in a new tab)JavaScript
"use strict";function total(a, a) {  return a;} console.log(010); delete total; with ({ total: 1 }) {  console.log(total);}
  • Duplicate parameter names are confusing because one name hides the other.
  • Legacy octal numbers like 010 look decimal to many readers. Use 0o10 for octal in modern code.
  • Deleting a plain variable never made sense as a cleanup tool. Variables are not object properties you can remove that way.
  • with changes where names come from, so strict mode bans it. A later lesson, Sloppy mode in depth, revisits why old code had it.
Syntax errors happen early

If a strict script has a syntax error, try/catch inside that same script cannot catch it, because the script never starts running. Your editor, browser console, or test runner reports it before execution.

Strict by default in modules and classes

SORT

ES2015 made strict mode the default for two important modern features: modules and classes. If your file is an ES module, or if code is inside a class body, you do not need to write the directive.

Modules and classes are already strictPop out in the code editor (opens in a new tab)JavaScript
// ES module file, or <script type="module">const moduleThis = this; class StrictCounter {  count = 0;  bump() {    return this.count + 1;  }} console.log(moduleThis === undefined);console.log(new StrictCounter().bump());

In a module, top-level this is undefined, not the global object. Inside a class body, methods and field initializers use strict rules too. This is one reason modern tutorials and tools prefer modules: they start from the safer mode.

Do you need to add a directive?
  • <script src="app.js"></script>
  • <script type="module" src="app.js"></script>
  • class Counter { bump() { return this.count + 1; } }
  • <script>total = 1;</script>
Try it yourself
0 of 4 correct

Decide whether each fragment needs "use strict"; to be strict, or whether JavaScript already makes it strict.

Choose a category for every card. You can change an answer at any time; Reset clears them all.
Classic scripts still exist

A plain <script> without type="module" is a classic script. Classic scripts are the place where the directive still matters most.

Where you will use this

You will not spend every day typing "use strict". You will spend every day benefiting from it. Frameworks, bundlers, and many editors produce or expect module code, so strict behavior is the normal modern starting point.

A real bug strict mode catchesPop out in the code editor (opens in a new tab)JavaScript
"use strict"; function saveProfile(profile) {  profile.naem = "Ada"; // typo: meant profile.name  return profile.name;} const profile = Object.freeze({ name: "Grace" });console.log(saveProfile(profile));

The typo naem would be easy to miss if JavaScript quietly added a new property. Because the object is frozen and the code is strict, the bug becomes a TypeError near the write. That is much easier to debug than a missing name later in the app.

  • Use modules when you can. They are strict automatically and fit modern tools.
  • When writing an old-style classic script, put "use strict"; first.
  • When reading older code, recognize sloppy behavior instead of copying it into new files.
  • When strict mode throws, treat the error as help: it found a bug early.

Common misconceptions

“Strict mode makes every program faster.”

It can remove confusing cases, but do not use it as a speed switch. Use it because it catches mistakes.

“A comment before "use strict" breaks it.”

Comments and whitespace are fine. A real non-string statement before it breaks the prologue.

“I can turn strict mode off later.”

No. Once code is strict, a later string cannot make that same code sloppy.

“Modules need "use strict" at the top.”

They do not. It is harmless, but redundant, because modules are strict by default.

“Strict mode fixes all bugs.”

It catches specific old-language hazards. Logic mistakes like adding the wrong number are still your job to test.

Directive prologue vs ordinary string
Looks likeWhere it appearsWhat it means
"use strict";At the start of a script or function, before ordinary statementsA directive that enables strict mode
"use strict";After console.log(...), let total = 0, or another ordinary statementAn expression statement whose value is ignored
A commentBefore the directiveIgnored by JavaScript; it does not end the prologue

Practice: spot strict mode

5 EXERCISES
Exercise 1 · Warm-upPredict the caught error

Read the code and predict the exact error name printed by the catch block.

Starter codePop out in the code editor (opens in a new tab)JavaScript
"use strict";
try {
  usernmae = "Ada";
  console.log("saved");
} catch (error) {
  console.log(error.name);
}

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · PracticeAdd strict mode correctly

    Rewrite the program as a classic script that opts into strict mode. What statement must be first?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    let total = 0;
    total = total + 1;
    console.log(total);

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeFind why the directive did not work

      This code creates a global instead of throwing. Type the short reason.

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      console.log("start");
      "use strict";
      missingName = 1;
      console.log(globalThis.missingName);

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeConvert a silent write into a caught error

        What error name proves the frozen-object bug was caught?

        Starter codePop out in the code editor (opens in a new tab)JavaScript
        "use strict";
        const account = Object.freeze({ role: "reader" });
        try {
          account.role = "admin";
        } catch (error) {
          console.log(error.name);
        }

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeReal-world choice: classic script or module?

          You are adding JavaScript to a small existing page. When would you choose <script type="module">, and when would a first-line directive in a classic script be enough?

            Quiz: check your understanding

            7 QUESTIONS

            Pick the best answer. For code questions, the tests for this lesson run the same snippets so the answers match real JavaScript.

            Lesson quiz · 7 questionsScore: first tries count
            1. Question 1 of 7What does strict mode mainly do for a beginner?

              Choose an answer to see the explanation.

            2. Question 2 of 7Which placement turns a classic script strict?

              Choose an answer to see the explanation.

            3. Question 3 of 7What does this strict program print?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              "use strict";
              try {
                total = 1;
              } catch (error) {
                console.log(error.name);
              }

              Choose an answer to see the explanation.

            4. Question 4 of 7What is this in a plain function call under strict mode?

              Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
              "use strict";
              function showThis() {
                console.log(this === undefined);
              }
              showThis();

              Choose an answer to see the explanation.

            5. Question 5 of 7Which code is strict without writing "use strict"?

              Choose an answer to see the explanation.

            6. Question 6 of 7Why can a late directive be dangerous when files are concatenated?

              Choose an answer to see the explanation.

            7. Question 7 of 7Which old feature does strict mode forbid because it makes names hard to predict?

              Choose an answer to see the explanation.

            Key takeaways

            • "use strict" only enables strict mode when it appears in the directive prologue of a script or function.
            • Strict mode turns several silent mistakes into visible errors, especially undeclared assignments and failed writes.
            • It also rejects confusing syntax such as duplicate parameters, legacy octal literals, deleting variables, and with.
            • Modules and class bodies are strict by default; classic scripts need the directive if you want strict mode.
            • You cannot turn strict mode off from inside strict code.

            Remember the one-liner.
            Strict mode is JavaScript's safer modern mode: it stops old silent mistakes so you can fix them early.

            Up next: Talking to the user.

            CompleteFrontend Clear concepts. Working examples.