What is strict mode and how do you enable it?

Asked 3 months ago
Updated 15 days ago
Viewed 170 times

0

What is strict mode and how do you enable it?

ng new my-app --strict


1 Answer


0

Strict Mode is a feature in JavaScript that helps you write cleaner, safer, and more secure code by enforcing stricter parsing and error handling rules.

What is Strict Mode?

Strict mode eliminates some silent errors and makes them visible (throws errors). It also prevents the use of unsafe or outdated JavaScript features.

Key Benefits:

  • Catches common coding mistakes
  • Prevents use of undeclared variables
  • Disallows duplicate parameter names
  • Makes debugging easier
  • Improves performance in some cases

How to Enable Strict Mode

You enable strict mode using a simple directive:

1. For Entire Script

"use strict";

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

2. Inside a Function

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

Example Without Strict Mode

x = 10; // No error (bad practice)
console.log(x);

Example With Strict Mode

"use strict";

x = 10; // ReferenceError

Important Rules in Strict Mode

  • No undeclared variables
"use strict";
a = 5; // Error
  • No duplicate parameters
function sum(a, a) { } // Error
  • No deleting variables
delete x; // Error
  • this behaves differently
    • In strict mode, this is undefined in functions (not global object)

When Should You Use It?

  • Always use strict mode in modern JavaScript development
  • Especially important for large-scale applications and production code

Pro Tip

If you're using modern JavaScript (ES6 modules), strict mode is automatically enabled.

answered 15 days ago by Anubhav Sharma

Your Answer