The modern language specification contains a number of incompatible changes compared to the old standard.
In order not to break the existing code, they are mainly included if there is a special use strict
directive. This directive is not supported by IE9-.
"use strict"
The directive looks like the string "use strict";
or 'use strict';
, and can stand at the beginning of the script, or at the beginning of a function, for example:
For example, assigning a variable without a declaration in the old standard was permissible, but in the modern one it is not.
Therefore, the following code will generate an error:
The directive must be specified before the code, otherwise it will not work:
At the function level
Suppose the code works only in the old mode, but we want to write new functions using the modern standard.
"use strict";
directive "use strict";
You can specify at the beginning of the function, then it will only act in it.
For example, in the code below, variables without declarations are used. But the error will be displayed only when the function is started, since it is it that works in strict mode:
There is no way to cancel the "use strict"
action.
If the directive is specified at the script level, it acts on all functions.
Should I use strict
?
Strict mode gives two things:
- Where the “old code” was in the old standard, the new one will have an error.
- Some language features work differently. More correctly, but in a different way. In the course of the textbook, we will see many concrete examples of these differences.
All this is good.
But the main problem with this directive is support for IE9 browsers, which ignore use strict
and work only in the old standard.
Indeed, suppose we, using this directive, developed the code in Chrome. Everything works ... However, the probability of errors at the same time in IE9- has grown! Since only the old standard is supported there, compatibility errors are possible. And debugging code to find these errors is much less pleasant in IE9 than in Chrome.
However, a strict regime is our future. Therefore, it is better to use it. But you need to know very well the differences in the work of JavaScript between the old and the new mode, so that the code you write does not “break” when launched in the old standard mode.
Comments
To leave a comment
Scripting client side JavaScript, jqvery, BackBone
Terms: Scripting client side JavaScript, jqvery, BackBone