JavaScript

What is and what does use strict in JavaScript?

March 8, 2022

What is and what does use strict in JavaScript?

In this article you will learn what use strict in JavaScript does, and why you should try this way of programming, making your way of programming better.

use strict in JavaScript thumb

Hey you programmer, all right? Let’s learn how to use ‘use strict’!

Strict Mode came with ES5 version of JavaScript, this programming mode prevents certain actions for the good of our code

We can say that some possible hacks to be done with JavaScript are eliminated, which makes it advantageous to use strict

The first point is that: all ES3 features that are deprecated, discontinued, will be disabled in strict

That is, you will get an error when using one of them

And some other practical examples of what happens with strict:

  • Using undeclared variables generates an error;
  • Using an undeclared variable inside one also generates an error;
  • Changing the value of a property that is not writeable generates an error;
  • Deleting an object or variable is not allowed;
  • Deleting roles is also not allowed;
  • Duplication of parameters in function is also not allowed;
  • Modifying an object’s getter property is not allowed;
  • You cannot delete undeleteable properties;
  • You cannot use eval as a variable name;

Anyway, strict mode helps you write more secure and consistent code

I advise you to adopt it and see that it will not harm you that much, but improve the quality of your code a lot

How to use ‘use strict’

We have two ways to declare ‘use strict’ so that it works correctly

One is at the beginning of the file, so all code will follow the strict rule

And you should declare it like this:

"use strict";

Another possibility is to declare it inside a function

So only the function will benefit from strict mode, take a look:

function myFunction() {
 "use strict";
 a = 'test' // An error will raise here!
}

Note: the ‘use strict’ must be at the beginning of the code, first line;

Conclusion

In this article we learned  what ‘use strict’ does in JavaScript, and also some of its code improvements

For example: not being able to use a variable without declaring it

Since in normal JS a global variable is created when this happens

Finally, we learned that strict should always be used at the beginning of the code or inside a function

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x