乐闻世界logo
搜索文章和话题

What does use strict do in javascript?

1个答案

1

use strict is a directive in JavaScript used to enable strict mode. It was introduced in ECMAScript 5 and has the following main purposes:

  1. Eliminate certain loose syntax features: In strict mode, coding practices that would not throw errors in non-strict mode now do. For example, assigning a value to an undeclared variable throws an error.
javascript
'use strict'; undeclaredVariable = 1; // ReferenceError: undeclaredVariable is not defined
  1. Eliminate silent errors: In non-strict mode, some type errors are silently ignored. However, in strict mode, these errors are thrown, making it easier for developers to detect and fix them.
javascript
'use strict'; false.true = ''; // TypeError: Cannot create property 'true' on boolean 'false' (14).sailing = 'home'; // TypeError: Cannot create property 'sailing' on number '14'
  1. Enhance compiler efficiency and improve runtime performance: Because strict mode avoids certain language features, JavaScript engines can more easily optimize the code.

  2. Disable certain confusing language features:

    • The with statement cannot be used, as it changes scope and causes optimization issues.
    • Assigning values to non-writable or read-only properties, adding new properties to non-extensible objects, or deleting non-deletable properties will throw errors.
    • Function parameters cannot have duplicate names, otherwise errors will be thrown.
javascript
'use strict'; function duplicateParam(p, p) { // SyntaxError: Duplicate parameter name not allowed in this context return p + p; }
  1. Prepare for future JavaScript versions: Strict mode disables certain syntax that may be given new meanings in future language standards, reducing backward compatibility issues.

How to apply use strict:

  • Apply it to the entire script by adding 'use strict'; at the top.
  • Apply it to a single function by placing it at the top of the function body.
javascript
function myFunction() { 'use strict'; // Function-level strict mode syntax var v = "Hi! I'm a strict mode script!"; }

Using strict mode helps improve code quality and maintainability, and makes JavaScript code more secure. However, it is important to be aware of potential compatibility issues when mixing strict mode and non-strict mode code.

2024年6月29日 12:07 回复

你的答案