[JS] – Use Strict is a good practice

What does it means ?

Defines that JavaScript code should be executed in “strict mode”.

How to use it ?

Strict mode is declared by adding “use strict”; to the beginning of a script or a function.

Examples

  • Declared at the beginning of a script, it has global scope (all code in the script will execute in strict mode):

“use strict”;
x = 3.14;       // This will cause an error because x is not declared. Eg for fix it var x = x = 3.14;

“use strict”;
myFunction();
function myFunction() {
y = 3.14;   // This will also cause an error because y is not declared
}
  • Declared inside a function, it has local scope (only the code inside the function is in strict mode):
x = 3.14;       // This will not cause an error.
myFunction();

function myFunction() {
“use strict”;
y = 3.14;   // This will cause an error
}

Why use Strict Mode? Why it is a good practice ?

This will avoid a lot of errors as:

  • Strict mode makes it easier to write “secure” JavaScript.
  • Strict mode changes previously accepted “bad syntax” into real errors.
  • As an example, in normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.
  • In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties.
  • In strict mode, any assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object, will throw an error.

What it not allowed in Strict Mode ?

  • Using a variable or object without declaration;

x = 3.14;

OR

x = {p1:10, p2:20};

  • Deleting a variable (or object), or function;

var x = 3.14;
delete x;

OR

function x(p1, p2) {};
delete x;

  • Duplicating a parameter name;

function x(p1, p1) {};

  • Octal numeric literals;

var x = 010;

  • Escape characters;

var x = \010;

  • Writing to a get-only or read-only property;

var obj = {};
Object.defineProperty(obj, “x”, {value:0, writable:false});
obj.x = 3.14;

OR

var obj = {get x() {return 0} };
obj.x = 3.14;

  • Deleting an undeletable property;

 

delete Object.prototype;
  • The string “eval” cannot be used as a variable

var eval = 3.14;

  • The string “arguments” cannot be used as a variable:

var arguments = 3.14;

  • The with statement

with (Math){x = cos(2)};

  • For security reasons, eval() to create variables in the scope from which it was called

eval (“var x = 2”);
alert (x);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s