It is a advisable to follow same coding style for all JavaScript code.
Coding convention are predefined guidelines for writing code. It includes
Coding convention makes it easier to maintain code in long term due to its unique defined styles.
Generally JavaScript programmers use camelCase for variable or function names.
Variable or function names starts with a letter.
streetName = "Wall street"; streetNumber = "10"; unitPrice = 15.5; taxAmount = 0.30; totalPrice = unitPrice + (unitPrice * taxAmount);
Always put spaces before and after operators and after commas. It will make code readable and clean. There are many online tools available to remove comments and extra white spaces from JavaScript code to make it small size for production.
totalPrice = unitPrice + (unitPrice * taxAmount); var makeNames = ["Audi", "Alpha-romeo", "BMW"];
Use spaces to indent code blocks. Generally 4 spaces are used for indentation.
All popular editors allows to change settings for tabs with spaces.
function multiply(a, b) { return a * b; }
Always write one statement per line. Always end a statement with semicolon(;)
streetName = "Wall street"; streetNumber = "10"; unitPrice = 15.5;
Some general rules for wring statements.
function square(num) { return num * num; }
for(i=0, len=Student.length; i<len; i++) { studentGrads[i] = getGrade(Student[i]); }
f($marks > 90) { document.write('Grade A'); }
switch(fruit) { case 'Apple': msg = 'Apple is of red color'; break; default: msg = 'Fruit is not available'; }
Place of opening and ending bracket is same as like on functions and loops except there should be a semicolan at the end of ending bracket
var addr = { street: "150 feet road", postal: "12345", country: "India" };
Objects can be written on one line using spaces between property, if it is completed within a line.
var addr = {street:"150 feet road", postal:"12345"};
It is a good practice to keep line length < 80 characters. If a statement does not fit in single line than break line in multiple lines
document.getElementById('testdemoelement').innerHTML = 'This is a long line, so it is better to split it in multiple lines';
Always define a common rule set for variable names for entire code. For example.
External JavaScript is added to an HTML page using script tag.
<script src="functions.js"></script>
Coding conventions are for more readability and maintain common structure for whole JavaScript code.
So it will not affect on performance. Extra spaces and comments are not harmful in small scripts.
For production version it is better to use minified versions of JavaScript.