Be the first user to complete this post

  • 0
Add to List

Why use javascript strict mode

If you ever wondered why it helps to have `use-strict' at the top of your javascript files, I hope this post will give you enough reason to keep using it in your future code.

NOTE: Browser support for strict mode can be checked here.
Strict mode does two main things.
  • It eliminates some silent javascript errors by throwing errors instead.
  • It prohibits syntax likely to be defined in the future versions of Ecmascript.
There are also two important things to keep in mind about strict mode. - It can be applied either to entire scripts or indivdual functions. - It must appear before all other statements inside the function or the file.

Examples

The following three examples demonstrate 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: Concatenating strict and non-strict scripts is problematic because the order in which they are included will determione if the concatenated script is in strict mode or not. If you're using require for ALL of your javascript code and only bundle your javascript in that manner, you're fine because the strict mode will be restricted to the contents of each file being required.

Some of the things that strict mode does to help you avoid silly mistakes are - Throws an error if you accidentally create a global variable. - Throws an error if you make incorrect assignments. E.g if you try to reassign a non-writable property defined using Object.defineProperty, or a getter only property or a fixed property - Throws an error if you are deleting an undeletable property like Object.prototype - Throws an error if function parameter names are not unique. - Throws an error if you have octal syntax. - Prohibits using the 'with' keyword. For a more detailed list, check out MDN docs.

References



Also Read:

  1. center using css
  2. Difference between async and defer attributes in script tags
  3. Getting started with localStorage vs sessionStorage in html5
  4. Two column layout in css
  5. Promise javascript examples