Strict Mode

Because JavaScript was designed to be highly forgiving, it historically allowed developers to write sloppy code without throwing explicit errors. For example, assigning a value to a variable you never declared using let or const would silently create a global variable, often leading to nightmare-level bugs.

Strict Mode is a way to force the JavaScript engine to follow a more restrictive set of rules.

The Benefits of Strict Mode

  1. Throws explicit errors for mistakes that normally fail silently.
  2. Prevents the accidental creation of global variables.
  3. Fixes mistakes that make it difficult for JS engines to optimize your code (meaning Strict Mode code often executes faster).
  4. Prohibits the use of certain syntax that might clash with future versions of JavaScript.

Enabling Strict Mode

To enable strict mode globally for an entire file, place the string "use strict"; at the very top of your script.

"use strict";

// This will now throw a ReferenceError instead of silently creating a global!
message = "moo!"; 
console.log(message);

You can also apply it to a single function:

function strictFunction() {
  "use strict";
  // Strict rules only apply inside here
}

Strict Mode in Modern Modules

Here is the best part: Modern ES6 modules run in Strict Mode by default.

If you are writing modern JavaScript using ES6 modules (whether in the browser or in Node), you do not need to manually write "use strict";. It is handled for you automatically.