javascript Use Strict
For a long time, JavaScript developed without any similarity issues. There were added some new attributes to the language, but old functionality didn’t change. That had the profit of never breaking the existing code. But the negative aspect was that any mistake or some imperfect decision made by the creators of JavaScript got stuck in the language forever.
When ECMAScript 5 (ES5) appeared in 2009, it added new attributes to the language and modified old ones. For keeping the existing ones working, you need to enable them with the command "use strict", which forces a program to work under a “strict” operating context.
The "use strict" directive is not a statement, but a literal expression, which was ignored by many earlier versions of JavaScript. The main aim of "use strict" is to indicate that the code should be executed in "strict mode". Almost all modern browsers support "use strict". When the new browser sees the keyword "use strict" it turns itself into strict mode operating.
Enable strict mode
We declare strict mode after adding "use strict" to the beginning of a function or a script. When it declared at the beginning of a script, it has a global scope, which means that all code in the script will execute in strict mode.
Example of the strict mode for a global scope:
"use strict" can be put at the beginning of the function body instead of the whole script.
Example of the strict mode for functions:
// not strict
function strict() {
// strict mode syntax in function
'use strict';
return "This is strict mode script!";
}
// not strict
But usually, people use it for the whole script as well.
Strict mode changes early accepted "bad syntax" into real errors. Below you can see the examples of the “use strict” with errors.
Example of the undeclared variable in strict mode:
Example of the variable or object without declaring it:
Example of the reserved words to declare variables:
There are some keywords that can’t be used as variable names in strict mode: implements, interface, let, package, private, protected, public, static, yield.
Example of the function’s undeclared variable in strict mode:
When strict mode is declared inside a function, it has local scope. In this case, only the code inside the function is in strict mode.
Example of the strict mode is declared inside a function:
Example of the deleting variables, object, functions in strict mode raises an error:
Example of the function arguments can’t be deleted and have the same name:
"Strict mode" reports errors on the following:
- Using a variable, without declaring it.
- Using an object, without declaring it.
- Using reserved keywords as variable names.
- Deleting a variable is not allowed.
- Deleting a function is not allowed.
- Duplicating a parameter name is not allowed.
- The word eval can’t be used as a variable.
- For security reasons, there is not allowed for eval() to create variables in the scope from which it was called.
0 Comments
CAN FEEDBACK
Emoji