EN
JavaScript - strict mode
0 points
In this article, we would like to explain what is strict mode in JavaScript.
We declare strict mode with "use strict";
directive at the beginning of:
- a function - so only code in the function will be executed in the strict mode (local scope),
- a script - so all the code in the script will be executed in the strict mode (global scope).
The "use strict"
is a literal expression that tells JavaScript to execute code in a strict mode. It was presented in ES5 (ignored by earlier versions of JavaScript).
Here are some main functionalities of the strict mode:
- it changes previously accepted "wrong syntax" into errors,
- it doesn't allow mistyping a variable name (which outside the strict mode creates a new global variable),
- any assignment to a non-writable / getter-only / non-existing property or non-existing variable/object will throw an error,
this
keyword in functions behaves differently, it refers to the object that called the function,- basically, strict mode makes it easier to write secure code in JavaScript.
- use variable or object without declaring it,
- delete variable, object or function (
delete
operator), - duplicate parameter name,
- use octal numeric literals,
- use octal escape characters,
- delete undeletable property (like e.g Array.prototype),
- use
eval
andarguments
keywords as the variable name, - use
with
statement.
Using a variable without declaring it:
- without strict mode
xxxxxxxxxx
1x = 10; // No errors, we create new global variable
2console.log(x);
- with strict mode
xxxxxxxxxx
1"use strict";
2x = 10; // In strict mode this causes an error
3console.log(x);
Using a variable without declaring it inside a function:
-
xxxxxxxxxx
1x = 10; // This doesn't lead to an error
2console.log(x);
3
4foo();
5
6function foo() {
7"use strict";
8y = 20; // This leads to an error
9}
10
11console.log(y);