Using strict mode to write secure Javascript

Using strict mode to write secure Javascript

We know that doing read operation from undeclared variable gives error in Javascript, whereas doing write operation to an undeclared variable is fine and the variable gets the global scope (I will discuss this in a different post as to why this happens in Javascript).

Now, lets take stock of a situation in Javascript.

var myName="";
myname="Anoop";

In the above, 1st statement declares a variable myName and we assign an empty string to it. However in the 2nd statement we want to assign something meaningful to this string but accidentally we misspelled the variable to myname. Guess! what happens.

Remember, what I said above that write operation to an undeclared variable is fine and the variable goes to global scope in Javascript, and global scope is bad generally. So, no error in executing above codes, but logically its a bug in terms of business logic. Strict mode in Javascript (as per ECMAscript 5 spec) comes to rescue.

So, lets apply strict mode to our code.

"use strict";
var myName="";
myname="Anoop"; // This will cause an error (myname is not defined)

Yup, thats it. Strict mode is declared by adding “use strict”; to the beginning of a script or a function. Strict mode restricts the undeclared variable write operation in Javascript. Declared at the beginning of a script, it has global scope (all code in the script will execute in strict mode). Strict mode changes previously accepted “bad syntax” into real errors.

If the strict mode is declared inside the function and at the beginning, then the strict mode is applied to the function only.

function myFunc(){
  "use strict";
  var myName="";
  myname="Anoop"; // This will cause an error (myname is not defined)
}

Leave a Reply

Your email address will not be published. Required fields are marked *