JavaScript Introduction | Exception Handling | Strict Mode
What Is Strict Mode?
Strict mode, first introduced in ECMAScript 5, applies stricter error checking to JavaScript code.
Strict mode can be declared by using the "use strict" directive at the beginning of a script or function.
"use strict" // Set the entire script to strict mode.
try {
num = 3.14; // Causes an error because an undeclared variable is used.
} catch (ex) {
document.getElementById("text").innerHTML = ex.name + "<br>";
document.getElementById("text").innerHTML += ex.message;
}
Strict mode declared this way strictly checks the code in the corresponding block according to strict mode syntax.
str = "Mistake!"; // An undeclared variable is used, but it is automatically declared as a global variable.
document.getElementById("noStrict").innerHTML = str + "<br>";
function StrictBlock() {
"use strict" // Set only this function block to strict mode.
try {
num = 123 // Causes an error because an undeclared variable is used.
} catch (ex) {
document.getElementById("funcStrict").innerHTML = ex.name + "<br>";
document.getElementById("funcStrict").innerHTML += ex.message;
}
}
StrictBlock();
In the global area that is not in strict mode in the example above, using an undeclared variable automatically treats it as a global variable. However, in a function block declared as strict mode, using an undeclared variable causes an error.
The major web browser versions that support strict mode are as follows.
| Directive | ie | chrome | firefox | safari | opera |
|---|---|---|---|---|---|
| use strict | 10.0 | 13.0 | 4.0 | 5.1 | 12.0 |
Characteristics of Strict Mode
JavaScript strict mode uses syntax that restricts some features of the existing JavaScript language. It also modifies several important features to provide enhanced security along with stronger error checking.
The syntax of strict mode that differs from existing JavaScript syntax is as follows.
| Target | Restriction |
|---|---|
| Variables | Undeclared variables or objects cannot be used. Variables declared inside the eval() function cannot be used outside it. |
| Properties | Read-only properties cannot be assigned to. The same property cannot be defined multiple times. |
| Functions | Functions cannot be declared inside statements or blocks. |
| Parameters | Parameter names must not be duplicated. Element values of the arguments object cannot be changed. |
| Strings | The strings "eval" and "arguments" cannot be used. |
| Octal | Octal values cannot be assigned to numeric literals. |
| this | If the value pointed to by this is null or undefined, it is not converted to the global object. |
| delete | The delete keyword cannot be used. |
| with | The with statement cannot be used. |
| Reserved words | The following reserved words cannot be used: implements, interface, let, package, private, protected, public, static, yield. |