We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Strict Mode

JavaScript is a loosey-goosey language, as we've learned. As such, it's easy to make mistakes that are hard to catch until a user is emailing you a bug report.

Strict Mode is a way to opt-in to a more restrictive set of rules that help you catch errors earlier. It was introduced in ES5. Some of the big differences between strict mode and "normal" (sloppy) JavaScript are:

  • Eliminates some silent errors by throwing them
  • Fixes some mistakes that make it difficult for JS engines to optimize code. Strict mode code can sometimes run faster than identical code that's not in strict mode.
  • Prohibits some syntax likely to be defined in future versions of ECMAScript
  • In the browser, this is undefined in global scope

Long story short, when possible, strict mode is a good idea.

To enable strict mode, you just need to "use strict" at the top of your file:

"use strict";

// your code here

You can also enable strict mode for a single function:

function strictFunction() {
  "use strict";
  // your code here
}

Strict Mode in Modules

Here's the best part: you only need "use strict"; at the top of non-es6 modules. ES6 modules, which we will learn next, are always in strict mode by default. That goes for the browser and Node.js.

We'll go more in-depth on Node and browser modules in a moment.

Assignment

JavaScript normally lets you get away with all kinds of nonsense, so let's do some JavaScript shenanigans:

message = "moo!";
console.log(message);
node strict.js

This works just fine, and you should see "moo!" printed to the console! However, if we enable strict mode, this will throw an error instead of silently creating a global variable.

With strict.js still throwing an error, run and submit the CLI tests.