Middle+
What is strict mode in JavaScript? What are the differences when it is enabled and when it is not? What restrictions does it impose?
sobes.tech AI
Answer from AI
Strict mode in JavaScript is a special mode that introduces stricter rules for syntax and code behavior, helping to avoid common errors and improve security.
Differences of strict mode:
- Enabled by the directive
'use strict';at the beginning of a script or function. - In strict mode, some unsafe or deprecated constructs are disallowed.
Main restrictions and changes in strict mode:
- Prohibition of using undeclared variables (e.g.,
x = 10;withoutvar/let/constwill cause an error). - Cannot delete variables, functions, or arguments (
delete x;will cause an error). - Prohibition of duplicate parameter names in functions.
- The value of
thisin functions called without a context will beundefinedinstead of the global object. - Prohibition of using reserved words as variable names (e.g.,
implements,interface). - Prohibition of assigning values to read-only or non-existent properties.
Example:
'use strict';
function test() {
x = 10; // Error: x is not declared
}
test();
Without strict mode, such code would create a global variable x, which can lead to hard-to-find bugs.
Thus, strict mode helps write more reliable and predictable code.