Strict Mode

What is Strict Mode?

Strict mode has been introduces in ES5.

Strict mode makes JavaScript to be interpreted with some differences to the generic mode - sometimes unofficially called the sloppy mode.

Strict mode is triggered through usage of use strict literal expression.

Not all browsers support strict mode.

ES5 Modules

Strict mode is automatically applied to ES5 modules.

ES6 Classes

Strict mode is automatically applied to ES6 classes.

Scripts & Functions

Strict mode can be applied manually to:

  • a whole script, or

  • a function.

To add the strict mode to the whole script add use strict literal expression before any statements and/or expressions.

'use strict'

const horse = 'Kelpie'
// ...

To add the strict mode to a function add use strict literal expression before any statements and/or expressions in the function's body.

function doSomethingStrictly() {
  'use strict'

  const horse = 'Kelpie'
  // ...
}

Strict Mode Features

The primary features introduced by the strict mode are:

  • additional runtime errors,

  • additional syntax errors,

  • enhancing security,

  • inaccessibility of caller, callee & arguments,

  • changed behaviour of this,

  • better optimization.

Additional Runtime Errors

Strict mode disallows assigning a value to a not yet declared variable. Such an operation in sloppy mode is allowed and creates a new global variable through adding a new property to the global object.

'use strict'

foo = 42 // ReferenceError: foo is not defined

Further, in strict mode trying to delete an undeletable object property such as prototype throws TypeError.

Additional Syntax Errors

Strict mode aims at throwing errors instead of silently failing them as sloppy mode sometimes does.

The following will throw a SyntaxError:

  • misusing of ES5 reserved keywords such as private, protected, public, static, interface and yield (some of which serve as placeholders for now for future ES versions),

  • declaring identical function parameter names,

  • employing the keywords arguments or eval as variable names or function argument names,

  • trying to delete variable names with delete keyword,

  • using with statement.

Enhancing Security

Strict mode does not allow eval to create a new variable in the scope that called it.

Inaccessibility of `caller`, `callee` & `arguments`

'caller', 'callee', and/or 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them. Such an operation throws TypeError.

Changed Behaviour of `this`

Please see LINK https://soundof.it/edit-page/javascript-tutorial#this.

Better Optimization

Some changes and restrictions introduced by the strict mode allows for better optimization of the JavaScript code.

One of such changes is that the arguments object in strict mode references a copy of named arguments and not the named arguments themselves.