Question

What "use strict" Does in JavaScript and Why It Matters

javascriptsyntaxjslintuse-strict

Question

I ran some JavaScript code through JSLint and got this warning:

// Warning: Missing "use strict" statement.

After searching, I noticed that some developers place this at the top of their code:

"use strict";

When I added it, the warning disappeared. However, it was not clear why this statement exists or what it changes.

What does "use strict"; do in JavaScript?

  • Why was it introduced?
  • How does it affect the way JavaScript runs?
  • Is it still relevant in modern JavaScript?
  • Do current browsers actually recognize and enforce it, or was it only intended for future use?

Short Answer

By the end of this page, you will understand what "use strict" is, why JavaScript introduced strict mode, what kinds of unsafe behavior it prevents, how browsers handle it, and when you still need to think about it in modern JavaScript code.

Concept

"use strict" enables strict mode in JavaScript.

Strict mode is a safer, more predictable way to run JavaScript. It was added to help developers avoid some of the language's older, error-prone behaviors.

In early JavaScript, certain mistakes were silently accepted. For example, assigning to a variable that was never declared would create a global variable instead of throwing an error. That made bugs easy to introduce and hard to find.

Strict mode changes this by turning some silent failures into real errors and by forbidding a few confusing language features.

For example:

"use strict";

x = 10; // ReferenceError: x is not defined

Without strict mode, that same code could create a global variable by accident.

Why it was introduced

JavaScript grew quickly, and some early design decisions made the language more permissive than ideal. Strict mode was introduced in ECMAScript 5 as a way to improve code quality without breaking older code.

Instead of changing all JavaScript behavior globally, the language added an opt-in mode. Developers could enable stricter rules in new code while old code continued to work.

What strict mode changes

Strict mode mainly helps in these areas:

  • Prevents accidental global variables
  • Makes some invalid assignments throw errors
  • Disallows duplicate parameter names in many cases
  • Changes the value of this in some function calls
  • Reserves some words for future language features
  • Removes or restricts some confusing legacy behaviors

Is it still relevant?

Yes, but with an important detail:

  • ES modules are automatically in strict mode
  • JavaScript classes are also strict by default
  • Older script files may still need "use strict"; if they are not modules

So strict mode is still relevant conceptually, even if you do not always write the string manually in modern code.

Do browsers support it?

Yes. Modern browsers have supported strict mode for many years. It is not just for future use. When a browser sees a valid strict mode directive like "use strict"; at the top of a script or function, it changes how that code is parsed and executed.

Mental Model

Think of JavaScript strict mode like turning on safety rules in a workshop.

Without strict mode, the workshop is permissive:

  • You can leave tools lying around
  • You can label things poorly
  • You can make small mistakes that nobody stops

The work may continue, but hidden problems build up.

With strict mode, the workshop supervisor steps in:

  • If you use a tool incorrectly, you get stopped immediately
  • If you try to put something in the wrong place, it is rejected
  • If your instructions are ambiguous, you must fix them first

So strict mode does not add new superpowers. It mainly makes JavaScript stricter, safer, and easier to debug.

Take Quiz

Syntax and Examples

To enable strict mode, place this directive at the top of a script or function:

"use strict";

Script-level strict mode

"use strict";

let name = "Ava";
console.log(name);

This applies strict mode to the whole script file.

Function-level strict mode

function greet() {
  "use strict";
  let message = "Hello";
  console.log(message);
}

This applies strict mode only inside that function.

Example: accidental global variable

Non-strict mode

function setValue() {
  value = 42;
}

setValue();
console.log(value); // 42

This is dangerous because value was never declared, but JavaScript creates it globally.

Strict mode

"use strict";

function setValue() {
  value = 42;
}

setValue(); // ReferenceError

Now JavaScript stops the mistake immediately.

Example: this behavior

"use strict";

function showThis() {
  console.log(this);
}

showThis(); // undefined

In non-strict mode, this in a plain function call often refers to the global object in browsers. In strict mode, it stays undefined, which is safer and less confusing.

Example: invalid assignment

"use strict";

let user = {};
Object.defineProperty(user, "id", {
  value: 1,
  writable: false
});

user.id = 2; // TypeError

Strict mode turns this bad assignment into an error instead of silently failing.

Step by Step Execution

Consider this example:

"use strict";

function updateScore() {
  score = 100;
}

updateScore();

Here is what happens step by step:

  1. JavaScript reads "use strict"; at the top of the script.
  2. The engine marks this script as running in strict mode.
  3. The function updateScore is created.
  4. updateScore() is called.
  5. Inside the function, JavaScript sees score = 100;.
  6. It tries to find a declared variable named score.
  7. No local, parameter, or outer declared variable named score exists.
  8. In non-strict mode, JavaScript might create a global variable.
  9. In strict mode, JavaScript throws a ReferenceError instead.
  10. Execution stops unless the error is caught.

Now compare with a correct version:

"use strict";

function updateScore() {
  let score = 100;
  console.log(score);
}

updateScore();

Step by step:

  1. Strict mode is enabled.
  2. updateScore is defined.
  3. The function is called.
  4. let score = 100; creates a local variable.
  5. console.log(score); prints 100.
  6. The function finishes normally.

The key idea is that strict mode catches undeclared-variable mistakes early.

Real World Use Cases

Strict mode matters in real programs because it helps catch bugs that are otherwise easy to miss.

1. Preventing accidental globals in large apps

In a large frontend app, a typo in a variable name can leak data into the global scope:

"use strict";

function saveSettings() {
  settngsSaved = true; // typo
}

Strict mode throws an error immediately instead of creating a bad global variable.

2. Safer utility functions

Shared helper functions should behave predictably. Strict mode makes this handling less surprising.

3. Library and package development

When writing reusable code, silent failures are dangerous. Strict mode turns many of them into visible errors.

4. Refactoring old code

When teams modernize legacy JavaScript, strict mode helps expose hidden problems early.

5. Better debugging in scripts and automation

For Node.js scripts, build scripts, or browser utilities, strict mode often makes mistakes fail fast rather than producing strange side effects later.

Take Quiz

Real Codebase Usage

In real projects, developers rarely add "use strict"; randomly. They use it in structured ways.

Common patterns

1. Module-based code

Modern ES modules are strict automatically:

export function add(a, b) {
  return a + b;
}

No manual "use strict"; is needed here.

2. Legacy script files

Older non-module files may still begin with:

"use strict";

This is common in older codebases or scripts loaded with plain <script> tags.

3. Bundlers and transpilers

Tools such as Babel or older bundlers often insert strict mode automatically into generated output.

4. Validation and guard clauses

Strict mode works well with defensive programming:

"use strict";

function divide(a, b) {
  if (typeof a !== "number" || typeof b !== "number") {
    throw new TypeError("Arguments must be numbers");
  }

  if (b === 0) {
    throw new Error("Cannot divide by zero");
  }

  return a / b;
}

Strict mode does not replace validation, but it makes the environment stricter and less error-prone.

5. Safer method calls

Because this is less forgiving in strict mode, codebases often prefer explicit object usage, arrow functions where appropriate, or .bind() when needed.

Common Mistakes

1. Thinking "use strict" is a normal string

It looks like a string, but at the top of a script or function it is treated as a directive.

"use strict";

If it appears in the right place, it changes how the code runs.

2. Putting it in the wrong location

Strict mode only works as a directive when placed at the start of a script or function body.

Works

function test() {
  "use strict";
  let x = 1;
}

Not useful as a directive here

function test() {
  let x = 1;
  "use strict";
}

By then, it is just an expression statement.

3. Forgetting that modules are already strict

This is valid but usually unnecessary in an ES module:

"use strict";
export const value = 10;

Modules are strict by default.

4. Confusion about this

Broken expectation:

"use strict";

function show() {
  console.log(this.name);
}

show(); // TypeError because this is undefined

Fix it by calling the function as a method or binding this properly.

5. Assuming strict mode fixes all bugs

Strict mode helps catch certain categories of mistakes, but it does not replace:

  • testing
  • type checks
  • validation
  • linting
  • good design

6. Enabling strict mode in old code without testing

Legacy code may depend on non-strict behavior. Turning on strict mode can reveal real bugs, which is good, but it may also require code changes.

Comparisons

TopicNon-strict modeStrict mode
Undeclared variable assignmentCan create a global variableThrows ReferenceError
Plain function call thisOften global objectundefined
Some bad assignmentsMay fail silentlyThrows error
Reserved wordsMore permissiveMore restricted
Legacy behaviorAllows more old patternsRejects some unsafe patterns

Strict mode vs linting

ToolWhat it does
"use strict"Changes JavaScript runtime/parsing rules
ESLint or JSLintAnalyzes code and warns about style or possible bugs

A linter can recommend strict mode, but strict mode itself is part of JavaScript.

Script vs module

Code typeNeed to write "use strict";?
Traditional script fileSometimes yes
ES moduleNo, already strict
Class bodyNo, already strict

So the concept still matters, but the manual directive is less common in modern module-based code.

Take Quiz

Cheat Sheet

"use strict";

What it does

  • Enables JavaScript strict mode
  • Makes code safer and less permissive
  • Turns some silent mistakes into errors

Where to put it

Entire script

"use strict";
// rest of file

Single function

function run() {
  "use strict";
  // function code
}

Important effects

  • No accidental global variables
  • this in plain function calls becomes undefined
  • Some invalid assignments throw errors
  • Some legacy syntax and behaviors are disallowed

Already strict by default

  • ES modules
  • Class bodies

Common example

"use strict";
x = 5; // ReferenceError

Good to remember

  • It must appear at the beginning of a script or function body
  • It is supported by modern browsers
  • It is still relevant, especially for understanding older code and JavaScript behavior

FAQ

Is "use strict" still needed in JavaScript?

It is still relevant, but in ES modules and classes strict mode is automatic. You usually add it manually only in older script-style code.

Do browsers support "use strict"?

Yes. Modern browsers have supported strict mode for many years.

Does "use strict" make JavaScript faster?

Its main purpose is correctness and safer behavior, not performance. Any performance effects are secondary.

What happens if I assign to an undeclared variable in strict mode?

JavaScript throws a ReferenceError instead of creating a global variable.

Can I use strict mode for just one function?

Yes. Put "use strict"; as the first statement inside that function.

Are ES modules automatically strict?

Yes. All ES modules run in strict mode by default.

Why did JSLint warn about missing strict mode?

Because strict mode helps catch common JavaScript mistakes and encourages safer code.

Take Quiz

Mini Project

Description

Create a small script that demonstrates the difference between non-strict and strict JavaScript behavior when handling undeclared variables and this. This helps you see exactly why strict mode was introduced and why it prevents subtle bugs.

Goal

Build a JavaScript file with a few short examples that show strict mode catching mistakes that non-strict mode would allow or hide.

Requirements

  • Create one example that assigns to an undeclared variable
  • Create one example that shows the value of this in a plain function call
  • Add "use strict"; to a version of the code and compare the results
  • Use console.log and try...catch so the differences are visible without crashing the whole script
Take Quiz

Keep learning

Related questions

View more