What is Strict Mode and why use it?
- Variable declaration is mandatory
- Disallows duplicate property and parameter names
- The eval() method is safer to use, but still considered evil in some cases.
- Deprecates the with statement
- Decreases the global namespace pollution
Where can I use Strict Mode?
If you are a Windows 8 Metro style apps HTML/JS developer, Strict Mode is automatically added to the project templates in Visual Studio 11 as WinJS supports Strict Mode.
Enabling Strict Mode
Applying Strict Mode is very easy to do. Just add the "use strict" directive to your code (it's a string literal so include the quotes). The physical location of the strict directive determines the scope of Strict Mode. Below is a table showing the relationship between Strict Mode and scope. This means you can turn Strict Mode on and off granularly in code.
|Beginning of any .js file||Global|
|Beginning of the script inside a <script> element.||<script> element|
|Preceding function block |
First line in function block
As you can see, Strict Mode is flexible but try to keep Strict Mode out of a global setting where possible when dealing with Web pages (HTML, ASP.NET, PHP, etc...). If other scripts include your script using Strict Mode, then Strict Mode could apply to the included scripts and that can create problems. However, you can get the same effect as global Strict mode by wrapping your code like so:
This creates a block around both functions and Strict Mode appears global to to the all code that exists in that block, essentially making strict container for that code.