What is "use strict" in Javascript?

January 31, 2019

Use strict is a feature introduced in ES5, where adding the string "use strict" to a context in your JS code will opt it into a stricter variant of Javascript, where certain unsafe actions are not allowed.

In strict mode you could expect:

  • To see more exceptions for things that you're doing wrong.
  • To not be able to make certain mistakes that'll make your code harder to perform for a Javascript engine.
  • To be stopped from using code that will be released as part of future ES versions (e.g. a variable name that'll be shadowed once a future version of ES comes out).

Quick example:

const func = () {
   'use strict'
   console.log("I'm running in strict mode")

console.log("I'm running in non-strict mode")

Keep in mind that, ES2015 modules run in strict mode by default:

const func = () {
   console.log("I'm a module, so I run in strict mode")

export default func

Examples of an error:

'use strict';

var undefined = "hello";
// Uncaught TypeError: Cannot assign to read only property 'undefined' of object '#<Window>'