Be the first user to complete this post
|
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.
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
- ES5 specification.
- MDN docs.
- Blog post by John Resig.
Also Read:
- Error: can not find module 'underscore'
- Array filterUntil function implementation for javascript
- Parse html response with fetch API
- css specificity interview question
- Getting started with automation testing for webrtc applications