HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Strict Mode

The "use strict"; directive was introduced in ECMAScript version 5. It is not a statement, but a literal expression, ignored by earlier versions of JavaScript. The purpose of strict mode is to indicate that the code should be executed in "strict mode".


Declaring Strict Mode

Strict mode is declared by adding "use strict"; to the beginning of a script or a function.

Global Declaration
"use strict";
x = 3.14; // Error: x is not defined
Inner Declaration
x = 3.14; // Allowed
function myFunc() {
  "use strict";
  y = 3.14; // Error: y not defined
}

Why use Strict Mode?

  • Error Prevention: It turns silent errors into real "throw" errors, meaning you can find bugs faster.
  • Security: It prevents accidental global variables (like forgetting let or var).
  • Optimization: It helps modern JavaScript engines optimize your code for better performance.
  • Future Proofing: It prevents using reserved keywords that might be used in future versions of JS.

Prohibited in Strict Mode

Strict mode makes it impossible to perform certain actions that would otherwise be allowed in "sloppy mode":

  • Using undeclared variables: x = 3.14;
  • Deleting objects/functions: delete x;
  • Duplicating parameter names: function x(p1, p1) {};
  • Octal numeric literals: let x = 010;
  • Writing to read-only properties: Assigning a value to a non-writable property.
Modern Note: JavaScript Modules and Classes automatically run in Strict Mode. You don't need to add the directive manually when using them!

Key Points to Remember

  • "use strict"; must be at the very top of its scope
  • It enforces cleaner and more secure code practices
  • Variables must be declared (let, const, or var)
  • The this keyword is undefined in global functions
  • It prevents the accidental deletion of vital code components
  • Essential for professional-grade, bug-free applications