JavaScript use strict Mode Explained

Learn JavaScript use strict mode, common strict mode errors, scope rules, and how strict mode helps catch mistakes early in scripts and functions.

Published

Updated

Read time 2 min read

Reviewed byDeepak Prasad

JavaScript use strict Mode Explained

use strict turns on strict mode in JavaScript. Strict mode makes the runtime reject a number of unsafe patterns, which helps catch bugs such as accidental globals, duplicate parameter names, and silent mistakes early.

It is a practical guardrail when you are writing browser code, Node.js scripts, or modules. In error-heavy code paths, it pairs well with JavaScript try catch because both aim to surface problems quickly.

Tested on: Node.js v20.18.2. A short note after each runnable snippet describes what you should see in the console.


Method 1: Enable strict mode in a script

Add the directive at the top of a script or function before any other statement.

javascript
"use strict";

try {
  x = 1;
} catch (error) {
  console.log("use-strict:", error.name);
}
Output

You should see one line logging use-strict: ReferenceError.

Strict mode stops the runtime from creating an accidental global variable named x.


Method 2: Catch stricter function rules

Strict mode rejects some patterns that normally fail silently, such as duplicate parameter names and assignments that would otherwise be ignored.

javascript
"use strict";

try {
  eval("function demo(name, name) { return name; }");
} catch (error) {
  console.log("strict-function:", error.name);
}
Output

You should see one line logging strict-function: SyntaxError.

Use this when you want your code to fail fast instead of continuing with a hidden bug.


Method 3: Use strict mode with Node.js modules

ES modules are strict by default, so the same safety rules apply even when you do not write the directive explicitly.

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

When you need old-style script behavior, add the directive yourself so the runtime treats the file in strict mode. That is the safest approach for code that depends on scope rules and hoisting behavior staying predictable.


Summary

JavaScript use strict is a simple way to make the runtime reject unsafe patterns and expose mistakes earlier. Use it in scripts and functions when you want stricter scoping, clearer errors, and safer code that behaves more predictably in browsers and Node.js.


Official documentation

Steve Alila

Specializes in web design, WordPress development, and data analysis, with proficiency in Python, JavaScript, and data extraction tools. Additionally, he excels in web API development, AI integration, …