Javascript Guidelines: Commenting
Javascript Guidelines: Commenting
Javascript Guidelines: Commenting
Commenting
It is assumed that you will want to document things like: namespaces, classes, methods, method parameters, etc.
Comments should generally be placed immediately before the code being documented. It must start with a /** seq
uence or //
Simple Documentation
Adding a description is simple, just type the description you want in the documentaton comment.
Special "documentation tags" can be used to give more information. For example, if the function is a constructor,
you can indicate this by adding a tag.
Documentation with tag to describe your code
/**
* Represents a video.
* @constructor
*/
function Video( title, user ){
//statements here
}
/**
* Represents a video.
* @constructor
* @param {string} title - The title of the video.
* @param {string} user - The user of the video.
*/
function Video( title, user ){
//statements here
}
Understandability
Choose easy to understand and short names for variables and functions.
Bad variable names
var x1 = '',
fe2 = '',
xbqne = '',
incrementerForMainLoopWhichSpansFromTenToTwenty = '',
createNewMemberIfAgeOverTwentyOneAndMoonIsFull = '';
Avoid using dash "-" as var name in javascript or class name in css, use camelcase and or underscore "_" to name
your vars and classes.
Var names
Long List of Variables? Omit the "Var" Keyword and Use Commas Instead
Long list of vars
...Should be rather self-explanatory. I doubt there's any real speed improvements here, but it cleans up your code a
bit.
HTML
CSS
/** IN CSS */
#my_div {
background-color: red;
}
#my_SecondDiv {
background-color: blue;
}
#my_ThirdDiv{
background-color: #000;
}
.js_myClass {
display: block;
width: 240px;
}
JS
/** IN JAVASCRIPT */
var myDivs = document.getElementsByClassname( 'js_myClass' ),
i = 0,
j = myDivs.length;
for( ; i<j; i++ ){
//Do something with myDivs[i]
}
Our Guidelines
Avoid 'eval'
The eval() function in javascript is a way to run arbitrary code at run-time. In almost all cases, eval should never be
used. If it exists in your page, there is almost always a more correct way to accomplish what you are doing. For
example, eval is often used by programmers who do not know about using Square Bracket Notation.
The rule is, "Eval is evil."
No inline JavaScript
Avoid inline JavaScript as much as you can, is better to load the scripts in external files, however, if you need to get
values from back end in the page please place the script at the end of the template.
<div id="footer-copyright">
<span id="copyright">Copyright © 2007-2014 Tube8.com, All Rights Reserved:
</span>
<div class="ascapContainer"></div>
<div class="rtaLogoContainer"><a
href="http://www.tube8.com/info.html#rta"></a></div>
</div><!--/footer-copyright-->
<script type="text/javascript">
/**
* HUBTRAFFIC SCRIPT TE-5017
**/
function mg_playerEvent(onSeek) {
//statements here
}
/* =========================================== */
/* FUNCTION TO CHECK IF THE USER IS LOGGUED IN */
/* =========================================== */
function downloadVideo() {
//statements here
}
/* ========================================= */
/* RELATED VIDEO BUTTONS NEXT AND PREV LOGIC */
/* ========================================= */
function updateRelated (page) {
//statements here
}
</script>
<!--HTML CODE HERE-->
<div id="footer-copyright2">
<span id="copyright2">Copyright © 2007-2014 Tube8.com, All Rights Reserved:
</span>
<div class="ascapContainer"></div>
<div class="rtaLogoContainer"><a
href="http://www.tube8.com/info.html#rta"></a></div>
</div><!--/footer-copyright2-->
Use Semicolon
//instead of
alert( 'I am not using semicolon' )
//please use
alert( 'I am using semicolon' );
//behaviour example
var idNumber = '1352544'; //the value is a string not an integer
if( idNumber == 1352544 ){ // true in some browsers
//statements here
}
if( idNumber == '1352544' ){ // true in all browsers
//statements here
}
if( idNumber === '1352544' ){ //true in all browsers
//statements here
}
if( idNumber === 1352544 ){ //false in all browsers
//statements here
}
Style
Always use braces & have them on the same line
Functions in JS
if( foo ){
alert( 'Hello world!' );
}
For Loop
Multiline conditions
Multiline statements
//this is good
if($(this).find("option:selected").val() == "Gender" ||
$(this).find("option:selected").val() == "Birth Year"){
//statements here
}
//this is better
if( $( this ).find( 'option:selected' ).val() === 'Gender' ||
$( this ).find( 'option:selected' ).val() === "Birth Year" &&
$( this ).find( 'option:selected' ).val() !== 'undefined' ){
//statements here
}
Beautiful Syntax
if / else / for / while / try always have spaces, braces and span multiple lines this encourages readability.
<script type="text/javascript">
// code here
</script>
//Good
var o = new Object();
o.name = 'Carlitos';
o.lastName = 'Way';
o.someFunction = function() {
console.log( this.name );
}
//Better
var o = {
'name': 'Carlitos',
'lastName' : 'Way',
'someFunction' : function() {
console.log( this.name );
}
};
//Note that if you simply want to create an empty object, {} will do the trick.
var o = {};
Array
//good
var a = new Array();
a[0] = 'Carlitos';
a[1] = 'Way';
//better
var a = [ 'Carlitos', 'Way' ];
Use JSON
When storing data structures as plain text or sending/retrieving data structures via Ajax, use JSON instead of XML
when possible. JSON (JavaScript Object Notation) is a more compact and efficient data format, and is
language-neutral.
Selectors
Use ID selector whenever possible. It is faster
$( '#js-loadMore' ) // FASTER
$( '.greyButton' ) // SLOWER
Use find() for Id->Child nested selectors. The .find() approach is faster because the first selection is handled without
going through the Sizzle selector engine.
Objects
In order to make code reusable let's divide the objects in two modules (files): the object file with all the core
functionalities and the controller file with all the set up and events. Both should share the same filename but as for
the controller let's add the following suffix "_controller.js", meaining if we have a terminator.js file we should have a t
erminator_controller.js file.
As convention let's use the object name convention where the object name starts with capital letter.
In the above filename example for the terminator.js file it should contain the object with the core functionality for
instance:
Objects
var Terminator = function() {
"use strict";
var Self = this; // Self var instead of this in order to avoid confusion between
this according to object and this according to jquery or functionallity
/**
* Let's leave the object to know if the code is running in a legacy browser
*/
Self.shittyBrowser = ( navigator.appName + " " + navigator.appVersion );
Self.isShitty = Self.shittyBrowser.match( ( /(Microsoft Internet Explorer).+(MSIE
7|MSIE 8\.)/gi ) !== null );
/**
* Init method to set up more vars or initialite methods inside the object
*/
Self.init = function( options ){
Self.params = options; //Let's keep the Self.params var as default to access all
the params / options inside the object
!Self.isShitty ? "THIS" : "THEN THAT" ; // In case we need to set up something for
shitty browsers
...AMAZING SET UP OR INIT METHODS HERE...
},
/**
* Method needed in the object
*/
Self.amazingMethod = function( location, newTag ){
...AMAZING CODE HERE...
};
}
Code for the terminator_controller.js should contain the whole set up for the object
Object_controller
var blockRender = new Terminator();
blockRender.init({
'key' : value,
...AMAZING SET UP 'key' : value HERE...
});
The idea about separating the object from the controller is to permit us the share the core functionalities even tho
there is a different set up, for instance, if there is a set up for pc ( elements and events ) and a different kind of set
up for mobile and tablets but all of them sharing the same core functionalities.In the above filename example for the
terminator_controller.js file it should contain the set up for the object.
0 */
2 */
1 */
0 */