1. JavaScript
  2. Advanced
  3. Strict Mode

Strict Mode

Last updated:

The strict mode allows your code to run in a ‘better’ operating context by enforcing couple of rules:

  • variables must be declared - any variable that has not been explicitly declared with the var, let, or const keywords will result in an error.
  • prevents “bad” statements from failing silently, now producing syntax errors.
  • makes it easier to write “secure” JavaScript - disables certain features that are considered to be problematic, such as with statements and implicit global variables.

Enable globally

'use strict';
x = 42;       // Error - x is not declared

NB: The 'use strict' statement will be ignored by old browsers that don’t support strict mode.

Limited strict

Strict mode can be enabled in a local context - eg: inside a function:

x = 42;     // No Error (strict mode not on here)

function myFunction() {
  'use strict';
  y = 42;   // Error - y is not declared
}

Resources