Why "Strict" at all?

Photo by Zan on Unsplash

Why "Strict" at all?

Today, we are talking about "Strict Mode". The reasons why it was introduced and how it can change the way your code will run.

So, the obvious question is

What is Strict Mode?

-> Javascript implicitly runs on "Sloppy Mode". Using "Strict Mode" forces Javascript to run in the restricted mode, this is where it eliminates silent errors that can possibly lead to bugs by throwing them as errors. All modern browsers highly support this.

Syntax

-> Just write 'use strict' or "use strict" on top of the file and you are good to go. One thing to note is, that it can be used for entire files

'use strict'
   var x = "This will work for the entire file."

and specific functions.

function checkStrict() {
'use strict'
   var x = 'I am under strict observation.';
   return x;
}
var y = 'My mistakes are overlooked, I am still sloppy.';

One exception is for modules as they are automatically in strict mode since they were introduced in ECMAScript 2015.

Rules

What makes it different?

Under strict mode, we get errors to problems that are generally overlooked in the sloppy mode. Some of which are discussed below.

- Declaration:

Depending on where it's used, it may take global as well as local scope as shown in the snippets above.

This means one can explicitly choose where to use the strict behaviour of Javascript and where to ignore it. Although it is advised not to mix-match the modes in a file.

- Working with variables.

Strict Mode prevents the creation of global variables without declaring them.

'strict mode'
newVar = 10;
//Will throw an Reference error.

This means we need to declare variables with var, let or const to not get an error. Also, it is not possible to delete a variable or an object under strict mode.

- Parameters duplication is not allowed.

function sum(x, y, x) { 
  'use strict';
  return x + y + x; 
}

In sloppy mode, the parameter that comes up later hides the former which can be confused as a typo. While here in strict mode, this will throw a syntax error.

- Working with objects.

Writing to a read-only or get-only property is not allowed. In both cases, a type error is thrown.

var obj1 = {};
Object.defineProperty(obj1, 'x', { value: 4, writable: false });
obj1.x = 5; 


var obj2 = { get x() { return 3; } };
obj2.x = 5;

These were some of the reasons how strict mode changes the way JS works in the browser.

Conclusion:

Strict mode eliminates silent errors by throwing them as they are ignored in general. it also points to the mistakes that prevent the JS engine to make optimizations.

REFERENCES :-

Strict Mode on MDN