Javascript “Use Strict”

Strict Mode in Javascript is something that I always hear about in various forums but never actually implemented it. Well, I thought this is a good opportunity to do some research on.

What is Strict Mode?

Strict mode makes several changes to normal Javascript semantics. Strict mode eliminates errors that would be ignored in non-strict mode, thus making javascript “more secured”. Strict mode prevents hard to catch bugs by ensuring that the syntax is locked down tighter. It is generally syntax that a user may not mean to put down, but has the potential to cause major headaches down the road.

Declaring strict mode is very easy! You simple type “use strict” as a string anywhere you would like it to be implemented. For example, if you want your entire script to be in strict mode you type it at the type of the file like this…

// File: myscript.js

'use strict';
var a = 2;

Or if you want to limit the strict mode to the lexical scope of a specific function, you can do so!

function doSomething() {
'use strict';

What is prevented in Strict Mode?

Now let’s get to the fun stuff by taking a look at some examples of using strict mode. Using a variable without declaring it will throw an error in strict mode. This is to prevent unintentionally creating global variables throughout your application. Like this….

"use strict";
x = 3.14; // This will cause an error
// Same for objects...
"use strict";
x = {p1:10, p2:20}; // This will cause an error

Deleting a variable or a function or an argument is a no-no in strict mode.

"use strict";
function x(p1, p2) {};
delete x; // This will cause an error

Duplicating a parameter name is not allowed in strict mode.

"use strict";
function x(p1, p1) {}; // This will cause an error

Reserved words in the Javascript language are not allowed in strict mode. The words are implements interface, let, packages, private, protected, public. static, and yield.

The examples mentioned above are just a few things that are not allowed in strict mode. Check out the documentation for a more comprehensive list.

When to use strict mode?

Strict mode should be used for the most part. This prevents the user from making silent errors that would be difficult to debug later on. However, there are some cases where strict mode should be avoided.

Even thought strict mode is support by many major browsers, one should still take precaution by checking out the list for browser support before using strict mode.

Also strict mode is not recommended for existing code as it could be prone to multiple errors. It is best to leave your existing code the way it was and to only use the strict mode when starting a new project.

I hope this blog has helped you understand the use of strict mode in javascript as much as I did!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.