Best Practices in Javascript


Javascript has been the most popular and wonderful language for the web development in years and It has certainly got no match. When we write javascript to make our web pages beautiful, interactive & dynamic, most of the time we tend to make some silly mistakes since it is a dynamically typed language we need to be extra careful with it. These mistakes won’t hamper the productivity of the code not prevent any functionality but it might affect the performance of the application and break your code after a while when complicated things come into play. So it is better to follow some thumb rules in order to make your code more beautiful, readable, & efficient. Most of the times developers worry “Will my code be efficient and performance ready when goes into production?” the answer to the question is unpredictable. So use the following best practices I am sharing with you today and your code will never let you down and will always be performance ready. I have gathered some best practices which are to be followed while writing scripts for the web. Please read with patience.

Ground Rules for the Javascript

1. Always use === instead of == & !== instead of !=
=== will not only check for the content but it will also check the contents against the data type
For example


if('5'==5)//true;which was not suppoed to be true
if('5'===5)//false (which makes sense)

So always use === & !==.

2. Always use the tags after the tag because if you have any error in your script or javascript code  your page atleast load properly and not break the flow.It also makes the page load faster since the DOM elements load first followed by the javascript.

3. Always execute your code in ‘strict ‘ mode. In ECMA5,’use strict ‘ was introduced to run your code in strict mode.

For instance

'use strict';

x=5;

will throw an error in the browser’s console because the variable x was never defined,In order to escape the error you can simply define it with the keyword var against it.If I have ‘use strict ‘ on top it will apply to the whole scfipt. So always use ‘use strict’ it will run your code in strict mode and will save against hidden warnings and errors.

For example in the example below ‘use strict ‘ is limited to one single function

y=5;
 function simpleFunction(){
 'use strict';
 var x=5;
 }

In the case there will be no error since y will not be executed in the strict mode. Now you all must be wondering why wont “y” run in strict mode. It is because “y” is not in the scope of ‘strict mode’ if you want your code to run in strict mode put it inside the ‘use strict’
you can also use ‘use strict ‘in JQuery like below

(function($){

'use strict';
 $(document).ready(function(){

//your code
 })

}(jQuery));

 

4. Always indent your code and give shorter name to your variables.It makes your code look beautiful and readable.

var fname,lnmae; //avoid using shortcuts
var firstName,lastName; //use this way instead

Also avoid long variable names

var radius_of_the_circle; //avoid

var circleRadius // right way

5.  Do not minify your code in development. Always minify your code when ready for the deployment because you might want to debugg your code while developing and it is very difficult and unlikely to debugg the minified code.

6. Don’t use global variables avoid them because if you use global variable any variable can override it from outside which will be pain again. If you still want to use, you can use them by having closures or anonymous function.

Like this

(function(){
 var globalVariable=0;
 function testGlobalVariable()
 {
 globalVariable+=1;

return globalVaribale;
 }

alert(testVariable());

});

Avoid 


<script>

var globalVariable=45;//example

</script>

<script src=globalVariable.js></script>

Now let’s say we have a global variable with the name “globalVariable” and we have a script followed by the first script in the above example and have the same variable name as that of global variable name in “globalVariable.js” then it will override the value of “globalVariable” and that’s what we don’t want ofcourse.So global variable should always be used inside the closure and anonymous function.

7. Try to write cleaner code

if(number%2==0)
 alert(even);
 else
 alert(odd);

Is similar to (shotcut notation use)

(number%2==0)?alert('evan'):alert('odd'); //use this instead

8. Use commenting in your code. It will help others understand your code in one go.Otherwise you youself wont be able to distinguish between things after awhile.So it is good to comment your code.

9. Use console feature to debug your code
console.log –shows logs in the browser console.
console.clear –to clear logs in the browser console.
console.table — to show only a few values in a table while dealing with the JSON data.
console.assert –to check any value and throw error or success on failure or success respectively.

10. Make use use of online javascript checking  tool like JSLint ,JSHint,JSFiddle,JSBeautifier,JSBin,plunker,jsmini &jspretty.

11. Keep DOM acces to minimum as DOM manipulation  andoperations are very expensive. Don’t do DOM manipulation inside the loop

12. Don’t not pass string to setInterval function but pass function.

setInterval(function(){//somecode},1000); //right way

setInterval(alert(“hi”),1000); //avoid using setInterval this way.

13.Declare all the variables at the beginning.

var firstName,lastName,middleName;  //right way of declaring variables.

var firstName;
firstName=”Deepak”;

var lastName;
lastName=”Mehra”; //avoid declaring variable this way

It will only increase the lines of codes so it is better to declare all the variable in the beginning.

14. Avoid heavy nesting in your code.


setInterval(function (req, res) {
   // inline callback function ...
    fetSomeData(server,function (data) {
      // some code
     getData(client, function(Data) {
         //some code
      });
   });
});

Avoid heavy nesting like above, make your code more modularize instead.

References
http://www.w3schools.com/

http://www.wikipedia.com/


KNOLDUS-advt-sticker

About deepak028

There is nothing much to describe me.However, I am a very ordinary person who believes in sharing knowledge.
This entry was posted in Scala and tagged , . Bookmark the permalink.

One Response to Best Practices in 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