The "use strict"; Defines that JavaScript code should be executed in "strict mode".
Why Strict Mode?
Strict mode makes it easier to write "secure" JavaScript.
Strict mode changes previously accepted "bad syntax" into real errors.
As an example, in normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.
In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties.
In strict mode, any assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object, will show an error.
The "use strict" directive was new in ECMAScript version 5.It is not a statement, but a proper expression, which was ignored by earlier versions of JavaScript.
The purpose of this is to indicate that the code should be executed in only "strict mode".
With strict mode, you can not, for example, use undeclared variables.
All modern browsers support "use strict" except Internet Explorer 9 and lower: Such as google chrome, firefox, opera.. etc
While Declaring Strict Mode:
Strict mode is declared by adding "use strict"; to the beginning of a script or a function.
It has global scope meaning, all lines in the code will execute in strict mode-
For example:
"use strict";
x = 3.14; // This will cause an error because x is not declared
Another similar example:
"use strict";
myFunction();
function myFunction() {
y = 3.14; // This will also cause an error because y is not declared
}
x = 3.14; // This will not cause an error.
myFunction();
function myFunction() {
"use strict";
y = 3.14; // This will cause an error
}
Using an object, without declaring it, is not allowed:
"use strict";
x = {p1:10, p2:20};
// This will cause an error
Deleting a variable (or object) is not allowed.
"use strict";
let x = 3.14;
delete x; // This will cause an error
Similarly,
Duplicating a parameter name is not allowed
Octal numeric literals are not allowed
Octal escape characters are not allowed
Writing to a read-only property is not allowed
The word arguments cannot be used as a variable
The with statement is not allowed
Top comments (0)