Programming, Scripts

Unethical and evil JavaScript coding

I love JavaScript and I admire the power of JavaScript since I have started writing client side script using JavaScript. We all know how JavaScript add power to our web application making it more dynamic and conventional. But I do also realize that there are some basic features and ways of writing scripts which is unethical, creating memory leakage, leaving slower performance and easy for malicious injection. Today I would like to share some of the best practices of writing ethical code using JavaScript and avoid demolish events of this scripting language.

Including JavaScript Files instead of embedding in HTML files

We should write our script in a separate .JS file and not embed in HTML files unless the code is specific to a single session. Embedding script in HTML file increase the weight of the page without any caching and compression techniques. Also <script src=*.js>  tag should be placed late in the body in order to avoid delays of script loading on other page components

Variable and Function Declarations

Minimize the usage of global variables and all variables should be declared using var statement before it is used. Minimize the usage of global functions.

Avoid String Concatenation

String concatenation can create major problems with IE garbage collection. Instead of concatenation try to use join.  Like instead of writing the code like this

var name = 'Joy';
var age = '37'
var myString = 'Hello World! My name is ' + name + ', and my age is ' + age;

We should use join like this

var name = 'Joy';
var age = '37'
var myString = ['Hello World! My name is ', name, ', and my age is ', age].join();

Also avoid building up of string across conditional statements/loops using concatenation. Instead of writing the code like this

var myArray = 'Array of integers';
for (var i = 0; i < 10; i++) {
myArray += i + '=' + func(i);
}

We should write the code like this

var stringBuilder = ['Array of integers'];
for (var i = 0; i < 10; i++) {
stringBuilder.push(i, '=', func(i));
}
var myArray = stringBuilder.join('');

Defining Class and closure creation

We should always avoid defining a class in such a way that every time an instance is constructed, a new function and closure is created. For example this line of code is wrong

var myClass;
myClass.Employee = function () {
this.func = function () {
return 'Hello';
};
}

Instead of this we should write the code like this

var myClass;
myClass.Employee = function () {
alert('Invoking');
}

myClass.Employee.prototype.func = function () {
return 'Hello';
}

With this no matter how many instances are constructed for myClass.Employee, only one function will be created for func and no closures are created

Avoid unnecessary initialization of instance variables

Avoid unnecessary initialization of code each time constructor is called by placing instance variable declaration on the prototype for instance variables  with value type. Hence instead of writing the code like this

var func = function () {
this.prop1_ = 1;
this.prop2_ = 'Hello';
this.prop3_ = false;
this.prop4_ = [];
};

We should write the code like this

var func = function () {
this.prop1_ = [];
};

func.prototype.prop2_ = 1;
func.prototype.prop3_ = 'Hello';
func.prototype.prop4_ = false;

Avoid memory leakage from closures

Creating a closure is relatively slower than creating a inner function without a closure which is also much slower than using a static function. Hence instead of writing a code like this

function funcTimeOut() {
var message = 'Hi, my name is Joy';
window.setTimeout(function () {
alert(message);
}, 100);
}

We should write the code like this

function messageAlert() {
var message = 'Hi, my name is Joy';
alert(message);
}

function funcTimeOut() {
window.setTimeout(messageAlert, 100)
}

eval() is a dangerous function and sometimes turns to be evil

Be judicious while using eval(). While eval() is a function property of global object which evaluates a JavaScript code represented as a string , it sometimes turns out to be evil  when we run eval() with a string that can be affected by a malicious party which might end up running a malicious script  in user’s machine.

Hence never use eval() to convert property names into properties like the following code

var name = { firstname: 'Joy', lastname: 'Ghosh' };
var propname = getPropName();
eval('var name = obj.' + propname);

Instead you can use eval() to evaluate a string of JavaScript statements like the following code

var x = 10;
var y = 20;
eval("x + y");
eval("if (x < y) { return (y - x); } else { return (x - y); }");

Use JavaScript first class functions

Try to use JavaScript first class functions instead of evaluating code snippets. Below is the following way we should use these functions

//DO NOT USE THIS
setTimeout(alert('hello world'), 1000);

//USE THIS
setTimeout(function () {
alert('Hello world');
}, 1000);


//DO NOT USE THIS
button.setAttribute('onclick', alert('Hello world'));

//USE THIS
button.addEventListener('click', function () {
alert('Hello world');
}, false);

Well there are more to learn and you can find lot many ways to write ethical code in JavaScript. I recommend you reading some of the good blogs written by people who have tried to give best coding practices for JavaScript.

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