What is “ use strict; ” in JavaScript, and what does it do?

If you have working with JavaScript over the last few years you will have no doubt come across this little snippet

[sourcecode language=”javascript” wraplines=”true” highlight=””]
"use strict";

Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a “strict” operating context. This strict context prevents certain actions from being taken and throws more exceptions.

Strict mode helps in a few ways:

  • It catches some common coding bloopers, throwing exceptions.
  • It prevents, or throws errors, when relatively “unsafe” actions are taken (such as gaining access to the global object).
  • It disables features that are confusing or poorly thought out.

Also note you can apply “strict mode” to the whole file… Or you can use it only for a specific function ( quoting from John Resig’s article):

[sourcecode language=”javascript” wraplines=”true” highlight=”04″]
// Non-strict code…

"use strict";

// Define your library strictly…

// Non-strict code…

So in nut shell if you want to get serious about your JavaScript use this, it will definitely go along way in helping you write better JavaScript.

Leave a Reply