The concept of strict mode was introduced from ECMAScript5. Strict mode allows strict global or local error condition detection within functions.

The advantage of using strict patterns is that errors in your code can be detected early and ECMAScript behavior that can cause programming errors can be caught.

Browsers that support Strict mode include Internet Explorer 10+, Firefox 4+, Safari 5.1+, and Chrome.

How to use strict mode

To choose to go into strict mode, pragma can be used :” Use strict”

  • Engines that support strict mode start this mode,
  • Engines that do not support this pattern ignore this compilation instruction when encountering an unassigned string literal.

1. If “use strict” is given in global scope (outside the function), the entire code uses strict mode. (If code with “use strict” is placed globally in another file, the JavaScript code in that file will also be in strict mode.)

2. You can also turn on strict mode only in functions, as follows:

function xiaozhima()

"use strict";

  // Other code

}

Copy the code

If you don’t want the entire code to be in strict mode, it is recommended that strict mode be turned on only in specific functions that need to be tested.

Strict vs. non-strict — variables

1. Create variables

In strict mode, there are restrictions on when and how variables are created.

  • In non-strict mode, global variables can be created as follows:
// Undeclared variables

a = 1;

// Non-strict mode: create global variables

// Strict mode: ReferenceError message = "Hello world! ";

Copy the code

A can be created as a global variable even if it is not preceded by a keyword such as var, and even if it is not defined as an attribute of some global object.

  • In strict mode, accidental creation of global variables is not allowed.
"use strict"

// Undeclared variables

a = 1;

// Strict mode: ReferenceError message = "Hello world! ";

Copy the code

In strict mode, however, if you assign a value to an undeclared variable, the code will raise a ReferenceError at execution.

2,deleteTo delete a variable

  • Non-strict mode allows this but fails (returns false).
var color = "red"

delete color;

// Delete variables

// Non-strict mode: silent fails

/ / returns false

Copy the code
  • In strict mode, deleting variables also causes errors.
"use strict"

var color = "red"

delete color;

// Delete variables

// Strict mode: Throws ReferenceError

Copy the code

3. Variable names

Strict mode also has restrictions on variable names.

In particular, you cannot use implements, interface, let, package, private, protected, public, static, and yield as variable names.

These are reserved words and may be used in future versions of ECMAScript. In strict mode, using the above identifiers as variable names results in syntax errors.

Strict vs. non-strict — objects

Manipulating objects in strict mode is more likely to cause errors than in non-strict mode. In general, non-strict mode silently fails and strict mode throws an error. Therefore, using strict patterns in development increases the likelihood of early detection of errors.

1. Manipulating an object’s properties causes an error in the following cases:

  • Assigning a read-only attribute throwsTypeError;
  • This works with a non-configurable video systemdeleteThe operator throwsTypeError;
  • Adding properties to nonextensible objects throwsTypeError.

2. Property names must be unique when using object literals. Such as:

// Same name attribute

// Non-strict mode: no errors, the second property prevails

// Strict mode: throws a syntax error

var person = {

  name"Nicholas".

  name"Greg"

};

Copy the code

The object person here has two properties, both named Name.

  • In non-strict mode:personThe object’snameThe property value is the second;
  • In strict mode: In strict mode, such code causes syntax errors.

Strict vs. non-strict — functions

1. The parameters of named functions must be unique

Take the following function for example:

// Repeat the name parameter

// Non-strict mode: no errors, only the second parameter can be accessed

// Strict mode: throws a syntax error

function sum (num, num){

  //do something

}

Copy the code
  • In non-strict mode: this function declaration does not throw an error. Only the second argument can be accessed through the argument name; the first argument must be accessed through the Arguments object.

  • Strict mode: The parameters of a named function must be unique. Will throw an error

2. In the function bodyarguments

The Arguments objects also behave differently in strict mode.

  • In non-strict mode, changing the values of named parameters is also reflectedargumentsObject, for example:
// Change the value of the named parameter

// Non-strict mode: changes are reflected in arguments



function showValue(value)

  value = "Foo";

  alert(value); //"Foo"

  alert(arguments[0]); // Non-strict mode: "Foo"

}

showValue("Hi");



Copy the code
  • In strict mode these two values are completely independent.
// Change the value of the named parameter

// Strict mode: changes are not reflected in arguments



function showValue(value)

"use strict"

  value = "Foo";

  alert(value); //"Foo"

  alert(arguments[0]); // Strict mode: "Hi"

}

showValue("Hi");



Copy the code

In the above code, the function showValue() has only one named argument value. This function is called with an argument “Hi” that is assigned to value. Inside the function, value is changed to “Foo”.

  • This change will also change in non-strict modearguments[0]The value of the
  • But in strict mode,arguments[0]The value of is still passed in.

Like variables, strict mode limits function names, disallowing implements, interface, let, package, private, protected, public, static, and yield.

3,ifDeclaring functions in statements results in syntax errors

A final restriction on functions is that they can only be declared at the top level of code and inside functions. That is, declaring a function in an if statement results in a syntax error:

// Declare functions in an if statement

// Non-strict mode: the function is promoted outside the if statement

// Strict mode: throws a syntax error



if (true) {

  function doSomething(){

  / /...

  }

}

Copy the code
  • In non-strict mode, the above code will run in all browsers,
  • In strict mode, however, this will result in syntax errors.

Strict vs. Non-strict — eval()

The much-maligned eval() function has also been improved in strict mode. The biggest change is that it no longer creates variables or functions in the inclusion context.

Such as:

// Use eval() to create variables

// Non-strict mode: the dialog box displays 10

// Strict mode: ReferenceError is raised when alert(x) is called



function doSomething()

  eval("var x=10"); 

  alert(x);

}



Copy the code
  • In non-strict mode, the above code creates a local variable x in the function doSomething(), and alert() also displays the value of that variable.

  • In strict mode, calling eval() in the doSomething() function does not create the variable X, so calling alert() causes a ReferenceError to be thrown because x is not defined.

Variables and functions can be declared in eval(), but these variables or functions are valid only in the special scope in which they are evaluated, and are then destroyed. Therefore, the following code can run without problem:

"use strict";

var result = eval("var x=10, y=11; x+y");

alert(result); / / = > 21

Copy the code

Here we declare the variables x and y in eval(), and then add them together to return their sum. Thus, the value of the result variable is 21, which is the result of adding x and y. When alert() is called, the value of the result variable is still valid, even though x and y no longer exist.

Strict vs. Non-strict — Eval vs. Arguments

  • Strict mode is explicitly prohibitedevalargumentsAs identifiers, they are also not allowed to read or write their values. Such as:
// Refer to eval and arguments as variables

// Non-strict mode: No problem, no error

// Strict mode: throws a syntax error



var eval = 10;

var arguments = "Hello world!";



Copy the code
  • In non-strict mode, it can be overriddeneval, you can also giveargumentsThe assignment. In strict mode, however, this will result in syntax errors.

The inability to use them as identifiers means that syntax errors will be thrown in any of the following ways:

  • Use var declarations;
  • Assign another value;
  • Try to modify the included values, such as ++;
  • Used as a function name;
  • Used as a named function parameter;
  • intry-catchUsed as an exception name in a statement.

Strict vs. non-strict — this

One of the biggest security issues in JavaScript, and one of the most confusing, is how to suppress the value of this in certain situations.

  • Null or undefined values are converted to global objects when the apply() or call() methods of functions are used in non-strict mode.

  • In strict mode, the function’s this value is always the specified value, regardless of what value is specified. Such as:

// Access properties

// Non-strict mode: access global properties

// Strict mode: Throw an error because this is null



var color = "red";

function displayColor()

  alert(this.color);

}



displayColor.call(null);

Copy the code

The above code passes null to displaycolor.call (),

In non-strict mode, this means that the function’s this value is a global object. The result is a pop-up dialog that says “red”.

In strict mode, the function’s this value is null, so an error is thrown when the attribute of null is accessed.

Strict vs. non-strict — other

1, abandonedwithStatements.

  • The with statement in non-strict mode can change the path to parse identifiers,

  • But in strict mode, with is simplified. Therefore, using with in strict mode results in syntax errors.

//with

// Non-strict mode: allowed

// Strict mode: throws a syntax error



with(location){ 

  alert(href);

}



Copy the code

2. RemovedJavaScriptOctal literals in

Strict mode also removes octal literals from JavaScript. Octal literals starting with 0 used to cause a lot of errors. Octal literals are no longer valid syntax in strict mode.

// Use octal literals

// Non-strict mode: the value is 8

// Strict mode: throws a syntax error



var value = 010;



Copy the code

Note ⚠️ : Parsing octal literals using parseInt() is treated as decimal literals beginning with 0 in strict mode. Such as:

// Parse octal literals with parseInt()

// Non-strict mode: the value is 8

Strict mode: the value is 10



var value = parseInt("010");

Copy the code

Article borrowed from: javascript advanced programming third edition

Mind mapping


This article is formatted using MDNICE