This is the 11th day of my participation in the August More Text Challenge. For details, see:August is more challenging

Other than using some third-party plug-ins, what other ways can you find some intuitive errors ahead of time? The answer is to use JavaScript’s strict mode.

What is strict mode

In ES5, JS first introduced the concept of strict mode, which checks your code for errors under more strict conditions, and can be used globally or locally (applied inside functions). Understanding the rules of strict schemas is essential, and in the future ECMAScript will gradually force strict schemas to be used globally.

How to use

Very simple, just provide a string that is not assigned to any variable. The string is:

"use strict"
Copy the code

You can declare this string anywhere in the JS file. If it is not declared inside a function, it means that the schema is referenced globally. An example of turning on strict mode inside a function is as follows:

function demo(){
	"use strict"
	// do something...
}
Copy the code

Create variables in strict mode

In non-strict mode, you can declare a global variable directly, instead of using the var, let, or const keywords, and you don’t report an error. Example:

a = 1;
Copy the code

If a variable is declared in strict mode, it is not allowed and a ReferenceError is thrown upon execution. And in strict mode, you are not allowed to call DELETE on a variable, which also results in a ReferenceError exception, which in normal mode returns false silently even on failure.

let a = 1;
delete a;
Copy the code

Objects in strict mode

When manipulating objects in strict mode, the following situations also raise an error throw exception:

  • Assigning a read-only attribute raises TypeError.
  • Using DELETE on a non-configurable property raises a TypeError.
  • Adding attributes to an object that does not exist raises TypeError.

In addition, in contrast to non-strict mode, declaring two duplicate attribute names also throws a syntax error. In normal mode, it does not, and only the last declared attribute takes effect.

const obj = {
	name: "Sam".name: "Echo"
}
Copy the code

It is worth noting, however, that this restriction has been removed in ES6, meaning that declaring a duplicate property in strict mode will no longer throw an exception.

Welcome to other articles

  • Internationalizing your website with Vite2+Vue3 | More challenges in August
  • Actual: Front-end interface request parameter confusion
  • Actual: Implement a Message component with Vue3
  • Actual: Vue3 to implement the Image component, by the way, support lazy loading
  • One Piece, Vue.js 3.0 brings what updates
  • This article digests the major new features of ES7, ES8, and ES9
  • Technical team’s common problems and solutions
  • 10 new features commonly used in ES6
  • Vue3’s Script setup grammar sugar is really cool