JavaScript : Use Strict

use strict';` is a directive introduced in ECMAScript 5 that enables a strict mode of operation for JavaScript code. When placed at the beginning of a script or a function, it instructs the JavaScript engine to enforce stricter parsing and error handling rules. Here's what it does:

1. Strict Mode Enforcement:

 

  • Error for Silent Failures : In non-strict mode, some JavaScript errors are ignored, leading to silent failures. In strict mode, these errors are turned into exceptions, making debugging easier.
  • Prevents Global Object Leakage : In strict mode, assigning a value to an undeclared variable results in a ReferenceError , preventing accidental creation of global variables.
  • Eliminates Octal Numeric Literals : Octal numeric literals (e.g., 012 ) are not allowed in strict mode, reducing confusion.
  • Makes eval() Safer : In strict mode, eval() creates its own lexical scope, preventing pollution of the outer scope.

2. Enhanced Security and Performance:

 

  • Optimizations : Some JavaScript engines can apply optimizations when running code in strict mode, leading to potential performance improvements.
  • Safer Code : Strict mode helps to write safer code by catching common programming mistakes and preventing insecure coding patterns.

Enabling Strict Mode:


To enable strict mode for an entire script, you place the use strict ';` directive at the beginning of the script:


'use strict';
// Your JavaScript code here

 

To enable strict mode for a specific function only, you place the use strict ';` directive at the beginning of the function:


function myFunction() {
    'use strict';
    // Your function code here
}

 

Considerations:

 

  • Strict mode is backward compatible, meaning it won't break existing code. However, it may change the behavior of some valid non-strict code.
  • It's recommended to use strict mode in all modern JavaScript code to benefit from its advantages and write safer, more maintainable code.
  • Strict mode is not supported in older browsers or in environments where compatibility is a concern.

Using strict mode helps catch common errors and enforce best practices in JavaScript development, leading to more robust and reliable code.