There are other benefits, too. Strict mode dictates certain semantics that make it easier to optimize your code behind the scenes, allowing better performance. Strict mode also locks down certain keywords being used in ES6 (like
yield), which helps future-proof your code.
Enabling Strict Mode
To enable strict mode globally, stick this at the top of your .js file:
That statement is known as a “directive prologue”, if you want to feel fancy about it. You can also enable strict mode on a more granular level by putting that statement at the top of a function:
You can even enable strict mode in stringified code passed to
eval() by putting that statement at the beginning of the string… but then I’d ask why you’re using
Side note, notice how the statement to enable strict mode is just a string, so older browsers that don’t know about strict mode will safely ignore it.
So what kinds of mistakes will strict mode catch? Misspelled variables, for one. Normally, undeclared variables are implicitly defined on the global object, which can lead to silent errors if you suck at spelling. With strict mode, line 4 throws “Uncaught ReferenceError: potatoe is not defined”:
Strict mode also stops you from accidentally setting the same property on an object twice. This throws “Uncaught SyntaxError: Duplicate data property in object literal not allowed in strict mode”:
Strict mode disables use of the
with statement. If you’ve never used
with, don’t worry about it, keep on not using it.
Those were just 3 examples, but the full list includes many more.
Browser support is strong, IE10+ and all the other big players. As mentioned before, non-supporting browsers will simply ignore it without error, so no worries.