In a non-strict-mode scope, when a variable is assigned without being initialized with the var
, const
or the let
keyword, it is automatically declared in the global scope:
a = 12;
console.log(a); // 12
In strict mode however, any access to an undeclared variable will throw a reference error:
"use strict";
a = 12; // ReferenceError: a is not defined
console.log(a);
This is useful because JavaScript has a number of possible events that are sometimes unexpected. In non-strict-mode, these events often lead developers to believe they are bugs or unexpected behavior, thus by enabling strict-mode, any errors that are thrown enforces them to know exactly what is being done.
"use strict";
// Assuming a global variable mistypedVariable exists
mistypedVaraible = 17; // this line throws a ReferenceError due to the
// misspelling of variable
This code in strict mode displays one possible scenario: it throws a reference error which points to the assignment's line number, allowing the developer to immediately detect the mistype in the variable's name.
In non-strict-mode, besides the fact that no error is thrown and the assignment is successfully made, the mistypedVaraible
will be automatically declared in the global scope as a global variable. This implies that the developer needs to look up manually this specific assignment in the code.
Furthermore, by forcing declaration of variables, the developer cannot accidentally declare global variables inside functions. In non-strict-mode:
function foo() {
a = "bar"; // variable is automatically declared in the global scope
}
foo();
console.log(a); // >> bar
In strict mode, it is necessary to explicitly declare the variable:
function strict_scope() {
"use strict";
var a = "bar"; // variable is local
}
strict_scope();
console.log(a); // >> "ReferenceError: a is not defined"
The variable can also be declared outside and after a function, allowing it to be used, for instance, in the global scope:
function strict_scope() {
"use strict";
a = "bar"; // variable is global
}
var a;
strict_scope();
console.log(a); // >> bar