1. Always use camelcase when declare variables.
❌ Don't Use
var first_name = document.ElementById("firstname").value;
var date_of_birth = document.ElementById("dob").value;
✔ Use
var firstName = document.ElementById("firstname").value;
var dateOfBirth = document.ElementById("dob").value;
2. Use shorten IF in small conditions.
❌ Don't Use
//Un-Compressed Code
if ( age < 19 ) {
isMajor = false;
} else {
isMajor = true;
}
✔ Use
//Compressed Code
isMajor = ( age < 19 ) ? false : true;
3. Declare Variables outside of loop.
Not in all cases. Do it when you use common components/functions/DOMs inside the loop.
❌ Don't Use
for(var i = 0; i < someArray.length; i++) {
var container = document.getElementById('container');
container.innerHtml += 'my number: ' + i;
}
/*
This will load the DOM each time of the loop.
Will slowdown your application performance in big cases.
*/
✔ Use
var container = document.getElementById('container');
for(var i = 0; i < someArray.length; i++) {
container.innerHtml += 'my number: ' + i;
console.log(i);
}
4. Reduce the single global variables.
❌ Don't Use
var userId = '123456';
var userName = 'username';
var dateOfBirth = '06-11-1998';
function doSomething(userId,userName,dateOfBirth){
//Your Implementation
}
✔ Use
//Make a collection of data
var userData = {
userId : '123456',
userName : 'username',
dateOfBirth : '06-11-1998'
}
function doSomething(userData){
//Your Implementation
}
function doSomethingElse(userData.userId){
//Your Implementation
}
5. Always comment your works & function input,outputs.
❌ Don't Use
function addNumbers(num1, num2){
return num1 + num2;
}
function getDataById(id){
return someDataArray[id];
}
✔ Use
/*
* Adding two numbers
* @para num1 (int), num2 (int)
* @return int
*/
function addNumbers(num1, num2){
return num1 + num2;
}
/*
* Adding two numbers
* @para id (int)
* @return Array
*/
function getDataById(id){
return someDataArray[id];
}
6. Always Build/Minify your JS before move it to live.
Commenting your works, New lines & other best practices will increase
your javascript file size. We need this stuffs in Development Environment only.
So Build & Minify your javascript file using build tools. It will compress your javascript to load much faster.
Asserts Build Tool : Webpack
Online Javascript Minifier : javascript-minifier
7. Load your scripts just before </body> Tags.
❌ Don't Use
<head>
<!--Don't Load JS files here.-->
</head>
<body>
<!--Don't Load JS files here.-->
✔ Use
<!--Load JS files here.-->
</body>
</html>