When, why and how to use the "use strict" directive in JavaScript?
I have never seen the use of this directive before, but almost all the more mature jQuery plugins use it.
I would like to know when and how to use it and what its purpose is.
6 answers
As others have said, strict mode is a stricter mode of language interpretation, which prohibits certain practices that have always been allowed but are not recommended (such as the creation of implicit global variables, already mentioned in other answers). Since simply unconditionally prohibiting this type of practice would break legacy codes, it was decided to create the "use strict";
directive to enable strict mode.
There are two ways to use the "use strict"
:
At the top of the file, the directive applies strict mode to the entire file.
As the first line of code for a function, the directive applies strict mode only within the function (including other functions that may be declared within it).
The great benefit of using strict mode is to reduce the chance of hard-to-find bugs in the code (such as a name conflict when creating an implicit global, or the existence of two equal keys in literal object).
I have prepared a free and adapted translation of the Annex C of the Language Specification, which summarizes the existing restrictions in strict mode:
The identifiers
implements
,interface
,let
,package
,private
,protected
,public
,static
, andyield
are reserved words when used in strict mode.-
Numeric literals are never considered octal, even when they begin with zero. We same goes for escaped octals in strings, like
'\012'
(which modern browsers don't even support anymore, even outside of strict mode) Trying to assign a value to a variable that does not exist in the current scope no longer creates a property in the global object (i.e. no longer creates a global variable). Instead, it throws an exception of type ReferenceError. Also, you cannot assign to properties that have the attribute {[[Writable]]:false}, nor to a accessor without setter defined ({[[Set]]: undefined}), nor for properties of objects whose internal property [[Extensible]] is false. In all these cases a TypeError will be thrown.
You cannot reset
eval
, or use it with++
or--
.If you try to access
arguments.caller
orarguments.callee
in a function, a TypeError is thrown.Named function arguments do not share values dynamically with the equivalent properties indexed numerically. For example, in
function foo(bar) { arguments[0] = 10; }
,bar
keeps the value passed in the call and does not assume the value10
.The same is true in the reverse case: in
function foo(bar) { bar = 10; }
,arguments[0]
keeps the value passed in the call and does not assume the value10
.If there is more than one property with the same name in a literal object, a SyntaxError is thrown.
The identifiers "eval" and "arguments" do not they can be used as function parameter names that define getters or setters on literal objects (even if the external code is not in strict mode, but the body of the getter/setter is).
eval
in strict mode cannot instantiate variables or functions in the scope of the callereval
. Code passed toeval
will create a new scope, where these variables will be instantiated.In strict mode, there is no coercion of
this
for object. In cases wherethis
isnull
orundefined
, it will not be converted to the global object. For example: infunction f(){ console.log(this) }; f();
,this
it isundefined
in strict mode, and not the global object (in browsers,window
). Also, if a primitive value is passed asthis
, it will not be converted to the equivalent wrapper.The
delete
operator throws a SyntaxError when used on non-deletable items such as variables, functions, and arguments. For example:delete variavel
,delete funcao
andfunction(foo) { delete foo; }
.The
delete
operator throws a TypeError if the property to be deleted has the attribute { [[Configurable]]:false }.If you try to declare a variable with the name of "eval " or" arguments", a SyntaxError is thrown.
Using
with
throws a SyntaxError.In a
catch
clause it is not possible to use "eval" or "arguments" as the exception name; this is a SyntaxError.The identifiers "eval" and "arguments" cannot be used as function parameter names; this is a SyntaxError.
Functions cannot have multiple parameters with the same name; this is a SyntaxError.
Implementations are prohibited from extending the meaning of the "caller" and "arguments" properties of function instances beyond what is in the specification.
It is a SyntaxError try using "eval" or "arguments" as a function or parameter name, as well as trying to force this through the
Function
constructor.
Javascript is a dynamic language that was not designed for the dimensions in which it is used today. So she's got some problems. For example the variable declaration, if you use a variable without var before, it becomes a global variable, so you might be overwriting a value that might be being used by some other function somewhere else. This kind of thing causes errors that are very difficult to find.
This type of behavior is" natural " of the language and would break a lot of existing libraries if it were taken out of the language now.
The "use strict" serves to try to mitigate these problems, browsers that recognize this directive will issue errors when they find code that is valid javascript but that is potentially problematic, such as the case of using variables without declaring with var. Old browsers that do not recognize simply ignore the directive.
And how the " use strict " can be used in blocks of code, you can use it within your new functions without having to refactor all your old libraries.
Example Of Use:
y = 2;//funciona sem problemas porque esta fora do bloco
function foo() {
"use strict";
x = 1;//emite erro em navegadores suportados
}
Reference: http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more /
'use strict' is used to expose the exceptions of your javascript code, seeing the errors in more detail
Example
function isStrictMode(){
return !this;
}
//retorna falso, uma vez que "this" se refere ao objeto global e '!this' se torna falso
function isStrictMode(){
"use strict";
return !this;
}
//retorna verdadeiro, pois no modo estrito, a palavra-chave "this" não se refere ao objeto global, ao contrário JS tradicionais. Então, aqui, "this" é nulo e '!this' se torna verdade.
JavaScript was originally designed to be easy to learn by inexperienced programmers. And so they've made JavaScript a language in which it's allowed to do all sorts of crap - the compiler rarely complains. I think everyone has already realized that it is preferable for the compiler to warn us of the mistakes we make, rather than silently ignoring the errors. The "strict mode" changes semantics from JavaScript to a more strict mode, in which probable error situations are you reject by the compiler. Example:
var length = 1;
...
lenght = 2; // "length" mal escrito - em JavaScript normal
// uma nova variável global chamada "lenght" é
// criada
'use strict';
var length = 1;
...
lenght = 2; // "length" mal escrito - em "strict mode" uma
// excepção é lançada
It is important to note that "strict mode" changes the semantics of the program. A program that worked correctly without " strict mode "may stop working with" strict mode " active. In addition, the" strict mode "is not supported by all browsers, and therefore it is necessary to be careful because code that works correctly with the" strict mode "active, may not work in browsers that do not support the"strict mode".
"use strict" is a directive in which you are telling the compiler not to allow you to make errors in your code that are not considered errors by the interpreter, but can cause you headaches. For example, Javascript allows you to use a variable without being declared, or to reset the variable arguments within functions:
The code below is considered valid without the use of the "use strict" directive:
function f() {
var arguments = [];
}
x = 0;
However, if used "use strict":
"use strict";
function f() {
var arguments = []; // SyntaxError: Variable name may not be eval or arguments in strict mode
}
x = 0; // ReferenceError: x is not defined
Caio Gondim wrote a very good article about the Infinite Loop that says the following:
Strict mode is a new feature in ECMAScript 5 that allows JavaScript code to run in a stricter mode. In this mode, the JavaScript engine has its behavior modified, generating errors that were previously silenced and even prohibiting the use of certain parts of the language that are considered problematic, thus forcing us to write better code quality and helping to catch bugs earlier.
There in the article he also exemplifies how to use. I suggest you take a look.
Http://loopinfinito.com.br/2013/07/16/javascript-strict-mode /