What does "use strict" mean in js code? What is the difference in using it

"use strict" is a directive to use strict mode. It is placed at the top of JavaScript code (usually in the function body or the first line of a script) and is used to specify that JavaScript code should be parsed and executed in a more strict manner.

The differences between using "use strict" include:

  1. Variables need to be declared first: In strict mode, variables must be declared before they are used. Otherwise, a ReferenceError will be thrown. For example:
'use strict';
x = 10; // 会抛出ReferenceError:x没有声明

  1. Deletion of variables is prohibited: In strict mode, the delete operator is not allowed to delete variables, functions, and function parameters. For example:
'use strict';
var x = 10;
delete x; // 会抛出SyntaxError:在严格模式下无法删除变量

function foo() {
  delete foo; // 会抛出SyntaxError:在严格模式下无法删除函数
}

  1. It is prohibited to use reserved words as variable names: In strict mode, some JavaScript reserved words cannot be used as variable names. For example:
'use strict';
var let = 10; // 会抛出SyntaxError:let是保留字,不能用作变量名

  1. Limit the use of this in functions: In strict mode, the value of this in a function will no longer be automatically converted to a global object or undefined, but will retain its original value. For example:
'use strict';
function foo() {
  console.log(this);
}
foo(); // 输出undefined而不是全局对象

These are just some of the changes in strict mode, there are many more restrictions and changes. Using "use strict" can help developers avoid some common mistakes and improve code reliability and performance.

Guess you like

Origin blog.csdn.net/m0_74265396/article/details/135435499