Concept:

Strict mode: Introduced in ES5, it is a way to automatically enforce stricter parsing and error handling when JavaScript code is running.

One of the features of the Javascript language is that it allows “dynamic binding”, which attributes and methods belong to an object, not at compile time, but at runtime.

Strict mode imposes some restrictions on dynamic binding. In some cases, only static binding is allowed. That is, which object attributes and methods belong to is determined at compile time. This makes compilation more efficient and makes the code easier to read with fewer surprises.

Position of use:

Strict mode can only be turned on if “Use strict” is placed at the start of a JavaScript file or function (the first line). It is recommended to put “use strict” at the beginning of the function rather than the beginning of the file.

Why is global “use strict” bad?

One important reason is that when non-strict mode files are merged with strict mode files, “use strict” goes into the middle of the file, not only does it not indicate strict mode, but it wastes bytes after compression.

The best way to overcome this limitation is to put the entire script file in an anonymous function that executes immediately.

(function (){
    "use strict";
    // some code here
})();
Copy the code

Advantages:

1. Catch code bugs that go unnoticed or fail silently early, making debugging easier.

2. Unexpected global variables. Without a strict schema, assigning a value to an undeclared variable automatically creates a global variable with that name. This is one of the most common mistakes in JavaScript. In strict mode, doing so throws an error.

3. Eliminate this coercion. If there is no strict mode, referencing null or undefined values to this values is automatically enforced on global variables. This can lead to a lot of headaches and hair-pulling bugs. In strict mode, referencing null or undefined this values throws an error.

4. Do not allow duplicate attribute names or parameter values. When duplicate named attributes are detected in an object, for example: var object = {foo: “bar”, foo: “baz”};) Or when duplicate named arguments are detected in a function, such as: function foo(val1, val2, val1){}) Strict mode throws an error, so catching a bug in your code is almost certainly a way to avoid wasting a lot of tracing time.

5. Make eval() safer. Eval () behaves differently in strict and non-strict modes. Most obviously, in strict mode, variables and functions declared inside an eval() statement are not created in inclusion scope (they are created in inclusion scope in non-strict mode, which is also a common source of problems).

6. Throw an error if delete is invalid. The delete operator (used to delete properties from an object) cannot be used on properties of an object that are not configurable. Non-strict code will silently fail when attempting to remove a non-configurable property, and strict mode will throw an exception in such cases.