Strict mode in JavaScript

Strict mode in JavaScript

Benefits of using Strict mode

What is strict mode?

  • strict mode is a special mode that we can activate in JavaScript which makes it easier for us to write a secure JavaScript code.
  • To activate strict mode, all we have to do is to write this at the beginning of the script.
"use strict";

With this we can activate strict mode for the entire script. One thing to know that the strict mode should be the very first statement in the script. If there are any code before this, then strict mode will not be activated. Comments are allowed since JavaScript will just ignore them but no code. We can also activate strict mode, only for a specific function or a specific block. But I don't see the point in doing that, instead we should use it at the beginning of each script.

When it is said that strict mode helps us to write secure code. By secure, it meant that strict mode makes it easier for us developers to avoid accidental errors. Basically, it helps us introduce the bugs into our code. That's because of 2 reasons:

  1. strict mode forbids us to do certain things.
  2. It will actually create visible errors for us in certain situations in which without strict mode JavaScript will simply fail silently without letting us know that we did a mistake.

Let us see an example of one of the important changes that strict mode introduces.

Example-1:

let hasDriversLicense = false;
const passTest = true;

if (passTest) hasDriverLicense = true;

if (hasDriversLicense) console.log("I can drive");

The Output is:

withoutStrictMode.png

Now let us see what will happen when we use strict mode.

"use strict";

let hasDriversLicense = false;
const passTest = true;

if (passTest) hasDriverLicense = true;

if (hasDriversLicense) console.log("I can drive");

The Output is:

withStrictMode.png

Here we can see that, by using strict mode in JavaScript we actually get an error. This error message tells us exactly what is wrong in the code. In the code, hasDriverLincense variable is not defined which should have been hasDriversLicense.

Another thing is that strict mode introduces a short list of variable names that are reserved for features that might be added to the language later.

Example-2:

"use strict";

const interface = "Video";

The Output is:

interface.png

What this message means is that JavaScript is reserving the word interface for a feature that it might implement in the future. And so, by reserving these kinds of words, it will then make it easier to implement the feature in the future.

Conclusion

In this article we discussed about what is strict mode, how to use it and benefits that be achieved using strict mode.

Wrap Up

Thank you for reading.

If you find this helpful, leave a like, share, and follow me, @srafsan to read more articles.