use strict

Strict mode in JavaScript causes your code to be interpreted under a stricter set of rules. JavaScript will nag you more and throw exceptions for things it previously had no issue with. This may not sound like a good time, but your code will be better for it. Strict mode is like a built-in linter, exposing bad practices and potential mistakes before they turn into hard-to-find bugs.

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 let and yield), which helps future-proof your code.

Enabling Strict Mode

To enable strict mode globally, stick this at the top of your .js file:

'use strict';

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:

function doStuff() {
  'use strict';

  // code
}

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 eval().

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.

Examples

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”:

'use strict';

var potato = 'russet';
potatoe = 'yukon gold'; // oops

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”:

'use strict';

var obj = {
  shape: 'octagon',
  color: 'blue',
  shape: 'triangle' // oops
};

Strict mode disables use of the with statement. If you’ve never used with, don’t worry about it, keep on not using it.

And More

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.