Vous êtes sur la page 1sur 17

Common Errors & Best Practices in Ja

vascript
Created By: Rohit Verma

Common Errors & Best Practices


Make things configurable
Always try to make things configurable managed from some property file (Like in validations and
messages).
// Bad Practice
If (emailAddressLength > 20){
alert(Email Address is invalid);
}
// Good Practice
// In Constants JS File MAX_EMAIL_ADDRESS = 20
If (emailAddressLength > MAX_EMAIL_ADDRESS){
//Display Error Message
}
In case max length of email address is changed at some later requirement then change will be d
one only at one place in Constants JS

Page 2

NEC Technologies India Limited 2013

Confidential for internal use only

Continued..
Do not add any JavaScript in the Html/Jsp files but add the Javascript code in a sepa
rate Js file and add the reference of the JS file in the Html/Jsp.

JavaScript references location in Jsp/Html

The JavaScript references should not be added on the top of HTML as while parsing the HTML
page if any JavaScript reference occurs somewhere in HTML then it loads the JavaScript first th
en continues loading the rest of the HTML which causes delay in loading the page.
// Bad Practice Adding the JS references on the top part of HTML
<html>
<head>
<script type="text/javascript" src="script1.js"></script>
<script type="text/javascript" src="script2.js"></script>
</head>
<body>
</body>
</html>

Page 3

NEC Technologies India Limited 2013

Confidential for internal use only

Continued..
//Good Practice (1) Add JS reference just before the closing of body tag
<html>
<head>
</head>
<body>
<script type="text/javascript" src="script1.js" </script>
<script type="text/javascript" src="script2.js"></script>
</body>
</html>
//Good Practice (2) using async loads the JavaScript asynchronously without causing any delay in
loading the HTML page
<html>
<head>
<script type="text/javascript" src="script1.js" async></script>
<script type="text/javascript" src="script2.js" async></script>
</head>
<body>
</body>
</html>

Page 4

NEC Technologies India Limited 2013

Confidential for internal use only

Continued..
//Good Practice (3) Using defer works same as adding the references at the end of the HTML, the J
avaScript is loaded at the end , after all the HTML DOM has been parsed
<html>
<head>
<script type="text/javascript" src="script1.js" defer></script>
<script type="text/javascript" src="script2.js" defer></script>
</head>
<body>
</body>
</html>

Note : Using async and defer are supported by almost all current versions of the browsers, however a very
few browser versions do not support them so they should be used accordingly.

Page 5

NEC Technologies India Limited 2013

Confidential for internal use only

Continued..
Do not add multiple validations code in a single JavaScript function but us
e utilities.
// Bad Practice
function checkValidations(){
if(emailAddressLength>20){
//Display error
}
if(telephoneNumberLength>10){
//Display error
}
if(telephoneNumber= ){
//Display error
}
}

Page 6

NEC Technologies India Limited 2013

Confidential for internal use only

Continued..
// Good Practice
function checkValidations (){
if(emailAddressValidation()){
//Display error and return
}
if(checkTelphoneNumValidation()){
//Display error and return
}
}

Compatibility View Issues


Always add the compatibility meta tags in Jsp if application works on Internet Explorer to display
the view in the latest compatible mode
<meta http-equiv="X-UA-Compatible" content="IE=edge">

Page 7

NEC Technologies India Limited 2013

Confidential for internal use only

Continued..
Declare all the JavaScript variables on the top.
//Bad Practice
var firstName=Mark;
var lastName=Johnson;
//Good Practice
var firstName, lastName;
firstName = Mark";
lastName = Johnson";

Always use === in place of == for comparison of values and type both
// Incorrect Results
1==1; //true
1== true; // true
// Correct Results
1===1; // false
1=== true; // false

Page 8

NEC Technologies India Limited 2013

Confidential for internal use only

Continued..
Automatic Type Conversions
JavaScript is loosely typed and can do automatic type conversions but be careful in case of the
mathematical operations
var x=5,y=10;
var z=x-y; // Correct Result -5
var z=x+y; // Incorrect Result 510
To avoid such problems always convert the values to numeric values before the mathematical o
peration (parseInt()).
var z=x+ parseInt(y); // Correct result 15

Page 9

NEC Technologies India Limited 2013

Confidential for internal use only

Continued..
Accidental use of assignment operators for comparisons
//Incorrect Result
var x=0;
if(x=10) // Always return true
//Correct Result
var x=0;
if(x==10)// Always return false
Floating point numbers calculation
All numbers in JavaScript are stored as 64-bits Floating point numbers (Floats).
Programming languages,including JavaScript, have difficulties with precise floating point value
s.
var x = 0.4;
var y = 0.2;
// Incorrect Result
var z = x + y
// the result in z will be 0.6000000000000001
if (z == 0.6)
// Always return false
//Correct Result
var z = (x * 10 + y * 10) / 10;
// z will be 0.6
if (z == 0.6)
// Always return true
Page 10

NEC Technologies India Limited 2013

Confidential for internal use only

Continued..
Breaking the String
JavaScript allows breaking the statement in two lines
//Correct
var x ="Hello World!";
Breaking a statement in the middle of a string will not work
//Incorrect
var x = "Hello
World!";
You must use a "backslash" if you must break a statement in a string
//Correct
var x = "Hello \
World!";

Page 11

NEC Technologies India Limited 2013

Confidential for internal use only

Continued..
Null and undefined checks
To be null, an object has to be defined first.
To test if an object exists below approach should be used
//Incorrect
if (myObj !== null && typeof myObj !== "undefined")
//Correct
if (typeof myObj !== "undefined" && myObj !== null)
Looping
// Bad Practice
for (i = 0; i < arr.length; i++) {
// Good Practice
length = arr.length;
for (i = 0; i < length; i++) {

Page 12

NEC Technologies India Limited 2013

Confidential for internal use only

Continued..
Do not get the JavaScript elements again and again in JavaScript but initial
ize once.
//Bad Practice
//Some place in JavaScript
document.getElementById(quantity).value=500;
//Some other place in JavaScript
document.getElementById(quantity).value=200;
//Good Practice
//Store all the elements initially
quantityObj= document.getElementById(quantity);
//Some place in JavaScript
quantityObj.value=500;
//Some other place in JavaScript
quantityObj.value=200;

Page 13

NEC Technologies India Limited 2013

Confidential for internal use only

Continued..
Caching Issues
Some times even after updating the JavaScript Code, On running the application the updated Ja
vaScript code does not reflect in the browser and application behaves abnormally, for that usuall
y we delete the browsing history and again start the application.
It is a very common problem while developing any web application ,to avoid such problems we s
hould add unique parameters in the JavaScript references.
<html>
<head>
</head>
<body>
<script type="text/javascript" src="script1.js?param=1.0" </script>
<script type="text/javascript" src="script2.js?param=1.0"></script>
</body>
</html>

Page 14

NEC Technologies India Limited 2013

Confidential for internal use only

Continued..
Minify JavaScript files
Generally in large scale web applications a lot of JavaScript files are used, in that case all the J
avaScript should be minified after the JavaScript code is fixed so that the performance can be i
mproved. There are many tools available to minify the JavaScript like minify etc.

Code Formatting
Code formatting is very important as now a days a major part of source code is written in JavaS
cript itself , If code is not formatted properly then the maintenance of JavaScript can be quite diff
icult, specially to a newcomer. For that when the JavaScript code get fixed once the code format
ter tool can be applied to the JavaScript for clean formatting.
There are a few online code formatting tools are available like jsbeautifier which can format the
JavaScript and HTML properly.

Page 15

NEC Technologies India Limited 2013

Confidential for internal use only

Thanks!!

Page 16

NEC Technologies India Limited 2013

Confidential for internal use only

Page 17

NEC Technologies India Limited 2013

Confidential for internal use only

Vous aimerez peut-être aussi