JavaScript Strict Mode

JavaScript Tutorial

JavaScript Strict Mode

Strict Mode is a feature in JavaScript that helps you write cleaner, safer, and error-free code by enforcing stricter rules.

To enable strict mode, add the line:

"use strict";

at the top of a script or function.


 Why Use Strict Mode?

Strict mode:

✔ Prevents the use of unsafe code
✔ Avoids common mistakes
✔ Makes debugging easier
✔ Improves performance in some engines


 Example 1: Using Strict Mode in Script

"use strict";

x = 10; // ❌ Error: x is not declared
console.log(x);

Without strict mode, this would create a global variable automatically.


 Example 2: Strict Mode in a Function

function test() {
"use strict";
y = 20; // ❌ Error
}
test();

🚫 What Strict Mode Disallows

Action Allowed Normally Allowed in Strict Mode
Using undeclared variables ✔ Yes ❌ No
Deleting variables ✔ Sometimes ❌ No
Duplicate parameter names ✔ Yes ❌ No
Using eval() to create variables ✔ Yes ❌ No
Using keywords as variable names ✔ Yes ❌ No

⚠ Example: Duplicate Variables Not Allowed

"use strict";
let a = 10;
let a = 20; // ❌ Error: duplicate declaration

🚫 Reserved Keywords Cannot Be Used as Variables

"use strict";
let public = 50; // ❌ Error

this Behavior Changes

In strict mode, this inside a function is undefined (not the global object).

"use strict";

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

checkThis(); // Output: undefined


🎯 Summary

Feature Strict Mode Effect
Prevents accidental globals ✔ Yes
Disallows unsafe syntax ✔ Yes
Helps avoid silent errors ✔ Yes
Makes code more secure ✔ Yes

Example (Good Practice):

"use strict";

let username = “Vipul”;
console.log(username);

You may also like...