Introduction
Strict mode is a way to introduce better error checking into your code. when you use strict mode, you cannot use implicitly declared variables, assign values to read-only properties, or add properties to objects that are not extensible.
Declaring strict mode
You can declare strict mode by adding "use strict" at the beginning of a file, program, or function. Such declarations are referred to as "instruction preamble". the scope of a strict mode declaration depends on its context. If strict mode is declared in the global context (outside the scope of the function), all code in the program is in strict mode. If you declare strict mode in a function, all the code in the function is in strict mode. For example, in the following example, all code is in strict mode, and a variable declaration outside the function causes a syntax error "undefined variable in strict mode".
[JavaScript]View Plaincopyprint?
- "Use strict";
- function TestFunction () {
- var testvar = 4;
- return TestVar;
- }
- There will be an error.
- TestVar = 5;
In the following example, only the code in TestFunction is in strict mode. a variable declaration outside a function does not cause a syntax error, but a declaration inside a function causes a syntax error.
[JavaScript]View Plaincopyprint?
- function TestFunction () {
- "Use strict";
- //There will be an error
- TestVar = 4;
- return TestVar;
- }
- TestVar = 5;
Javascript Strict mode