← Back to JavaScript Course | Chapter 6: Functions Advanced | Lesson 6 of 8

JS Strict Mode

Strict mode makes JavaScript stricter about mistakes, like a teacher who stops you when you are sloppy. It turns silent errors into clear messages.
Syntax
javascript
"use strict";

// strict mode code

What Is Strict Mode?

Strict mode makes JavaScript more careful. It catches some common mistakes. Enable it by adding 'use strict'; at the top of a file or function, which changes several silent failures into thrown errors instead.

उदाहरण: What Is Strict Mode?

javascript
"use strict";
console.log("Strict mode is on for this script.");

Prevent Accidental Globals

Strict mode prevents assigning a value to an undeclared variable. Without strict mode, x = 5 on an undeclared variable quietly creates a global variable — strict mode throws a ReferenceError instead, catching the typo immediately.

उदाहरण: Prevent Accidental Globals

javascript
"use strict";
try {
  x = 5; // undeclared variable
} catch (e) {
  console.log(e.message); // ReferenceError
}

Strict Function Calls

In a strict regular function call, this is undefined instead of the global object. This difference matters for code relying on this to detect whether a function was called as a standalone function versus as an object method.

उदाहरण: Strict Function Calls

javascript
"use strict";
function show() {
  console.log(this); // undefined, not global object
}
show();

Strict Function Parameters

Strict mode rejects duplicate parameter names. Use clear and unique parameter names.

Without strict mode, function f(a, a) {} silently allows the duplicate and the second a shadows the first — strict mode throws a SyntaxError instead, surfacing the mistake early.

उदाहरण: Strict Function Parameters

javascript
"use strict";
try {
  eval("function f(a, a) {}"); // duplicate parameter names
} catch (e) {
  console.log(e.constructor.name); // SyntaxError
}

Best Practice

Use strict mode in older script-based code when you want stronger error checking. Modern JavaScript modules are strict by default.

Since ES module code and class bodies are automatically strict, most modern JavaScript benefits from these protections without an explicit directive.

उदाहरण: Best Practice

javascript
class Example {
  // class bodies are strict by default, no directive needed
  show() { console.log(this); }
}
new Example().show();
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.