Skip to main content

JavaScript "Use Strict" Mode

By SamK
0
0 recommends
Category(s)
Topic(s)

The "use strict" directive in JavaScript enforces a stricter set of rules to help catch common coding mistakes and prevent unsafe actions.

Enabling Strict Mode

Strict mode can be enabled by adding "use strict"; at the beginning of a script or function.

Strict Mode for an Entire Script

"use strict";
x = 10; // Output: Error: x is not defined
console.log(x);

Strict Mode for a Specific Function

function myFunction() {
 "use strict";
 y = 20; // Output: Error: y is not defined
}
myFunction();

Benefits of Strict Mode

  • Prevents accidental global variables
  • Throws errors for unsafe actions
  • Disallows duplicate parameter names
  • Restricts use of reserved keywords for future-proofing

Common Errors Caught by Strict Mode

Prevents Accidental Global Variables

"use strict";
x = 5; // Output: Error: x is not defined

Disallows Deleting Variables & Functions

"use strict";
let name = "John";
delete name; // Output: Error: Cannot delete variable

Throws Error for Duplicate Parameter Names

"use strict";
function myFunc(a, a) {  
 return a; // Output: Error: Duplicate parameter name
}

Prevents this from Referring to Global Object

"use strict";
console.log(this); // Output: undefined instead of window

When to Use "use strict"

  • Always use it in new JavaScript code.
  • Include it at the beginning of functions to avoid affecting third-party scripts.
  • Helps write cleaner, bug-free, and optimized JavaScript.

Questions & Answers