How to Write Better JavaScript Code | JavaScript in HTML

How to Write Better JavaScript Code | JavaScript in HTML

  • Undeclared variables can cause very serious kind of effects which are very hard to detect. So always declare variable while writing JavaScript code.
  • As in most of the programming languages, terminate the statements by semicolons.
  • It is better to use namespace instead of global variable. It will prevent the collisions with other script libraries.
  • Using a coding notation method can help reading a script so always try to use one like Hungarian notation.
  • You should avoid language constructs like “eval()” etc, because it will make the code hard to read and maintain as well.
  • It will be better to use the built-in libraries of JavaScript when you need some like date, string, regular expression classes, sort()(for sorting array elements), reverse(for sorting array elements in reverse order), push() and pop() etc. The benefit of the use of these is that you don’t have to write code for these purposes.
  • Using anonymous function is nice way of writing the function in you page.  They allow you to skip a step and just declare and assign them as you would any other variable.

Here is an example of an anonymous function

Window.onload = function (){

Alert(“Welcome to howtocode.pk”);

}

  • You should keep in mind that the objects are associative arrays. So we can write object.property and object[property] as well.
  • Keep in mind that the associative array keys are converted into strings when we use them i.e. object[5+6] is the same as object[‘11’].
  • You should watch out for the modification of objects inside of a loop.
  • Avoid using ‘width’ statement in you code. There is a more efficient way instead. For example in the below code:

Width(test.information.settings.files){

primary = ‘names’;

secondary = ‘roles’;

tertiary = ‘references’;

}

More efficient way to deference the objects

Var temp_var = test.information.settings.files;

temp_var .primary = ‘names’;

temp_var.primary= ‘roles’;

temp_var= ‘refrences’;

Avoid passing strings to setTimeout() or setInterval(), because the JavaScript interpreter will have to interpret them, us functions instead. For example

setInterval(“displayMyData()”, 2000);

setTimeout(“moveElementBy(x); x+=5”, 2000);

The more efficient way will be:

function displayMyData(){ …………};

setInterval(displayMyData, 2000);

setTimeout(function(){

moveElementBy(x);

x+=5;

})

Instead of using DOM you should use the innerHTML property for processing large chunk of markup.

Comments