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:
this is undefined in global scopeLong 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
}
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.
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.