Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Why use javascript strict mode

If you ever won­dered why it helps to have ‘use-strict’ at the top of your javascript files, I hope this post will give you enough rea­son to keep using it in your future code.

NOTE: Browser sup­port for strict mode can be checked here.

Strict mode does two main things.

  • It elim­i­nates some silent javascript errors by throw­ing errors instead.
  • It pro­hibits syn­tax likely to be defined in the future ver­sions of Ecmascript.

There are also two impor­tant things to keep in mind about strict mode.
– It can be applied either to entire scripts or indi­v­d­ual func­tions.
– It must appear before all other state­ments inside the func­tion or the file.


Exam­ples

The fol­low­ing three exam­ples demon­strate how you can use strict mode in your code.

file1.js

'use strict';
...
...
...

OR

file2.js

// Its OK to have a comment here
'use strict';
...
...
...

OR

file3.js

function one() {....}

function two() {
    'use strict';
    ...
    ...
}

NOTE: Con­cate­nat­ing strict and non-strict scripts is prob­lem­atic because the order in which they are included will determione if the con­cate­nated script is in strict mode or not. If you’re using require for ALL of your javascript code and only bun­dle your javascript in that man­ner, you’re fine because the strict mode will be restricted to the con­tents of each file being required.

Some of the things that strict mode does to help you avoid silly mis­takes are
– Throws an error if you acci­den­tally cre­ate a global vari­able.
– Throws an error if you make incor­rect assign­ments. E.g if you try to reas­sign a non-writable prop­erty defined using Object.defineProperty, or a get­ter only prop­erty or a fixed prop­erty
– Throws an error if you are delet­ing an undeletable prop­erty like Object.prototype
– Throws an error if func­tion para­me­ter names are not unique.
– Throws an error if you have octal syn­tax.
– Pro­hibits using the ‘with’ keyword.

For a more detailed list, check out MDN docs.

Ref­er­ences

Ryan Sukale

Ryan is a UX engineer living in San Francisco, California.