Strict mode is implemented to make your program or function follow a strict operating context. It means, the errors which were being ignored by the compiler, will now throw exception messages.
So how do we change our mode from sloppy (non-strict mode) to strict? It’s easier than you think, just add the string “use strict” at the top of the program or a function and voila, you are in strict mode.
*Note: always remember “use strict” cannot be written as use strict directly. It is a string, which the compiler interprets to change the operating context.
*Fun fact: When “use strict” was first introduced, a lot of the older browsers did not support it. If one were to use ‘use strict’ directly, exceptions would get thrown. To avoid this, its invocation was declared as a string. If the browser didn’t support the feature, it would just ignore it as a string.
Defining the scope, when using “use strict” is also important. As the strict mode brings a new operational context, it might not be the best decision to use it all the time. Eventually, it all depends on the code requirements.
Let’s look at the different scenarios, where this simple change can help you.
A variable will not get added to the global/window object if it is not declared.
By default, if an undeclared variable is defined, it gets added to the global/window object. This can create an error and may even be hard to find.
To avoid such scenarios, we can declare use strict. Strict mode does not let the use of variables which have not been declared.
One cannot declare variables which might be used as future reserve words.
As we can see in the above example, on the left side we were able to declare a variable and name it let which is an ES6 reserved keyword. Technically this should throw an exception, but is ignored by the compiler.
Also, we can see on the right side, we got a syntax error by changing to a strict operation context. We should opt for strict mode, to avoid using a reserved keyword for variable names.
It stops one from deleting function, variables and function arguments:
The delete operator in itself is used to remove a property on an object.
The delete operator cannot be used to delete a function, variable or arguments.
When in strict mode it will throw a Type Error exception. This happens because we are trying to delete a property but the value itself.
The use of eval gets restricted:
Let’s try to implement the same code in strict mode:
In strict mode, eval is not executed, thus it gives us a reference error. The use of eval is never really advised, as there are far too many drawbacks of using eval. For a better understanding of the use of eval, you can go through the Mozilla docs.