You are on page 1of 23

Best Code Practices & Tips and Tricks

What is Javascript & jQuery


JavaScript jQuery
Query is a multi-browser JavaScript library
Developers need to handle by writing
designed to simplify the client-side
their own Javascript code.
scripting of HTML.
If you use Jquery, you need not to write
If you use JavaScript, you need to write
much scripting which already exists in
you own scripting which may take time.
JQuery.
JQuery is a framework built with
JavaScript to help JavaScript programmers
JavaScript is a language. Example: JQuery who are doing common web tasks.
like a foriegn language which is already Example: But if you goto a country where
built by Javascript which is unknown to it is spoken, a guide can still help you
you what kind of JS is written there, you along, making your journey easier. jQuery
are just using it. is one of many frameworks which provide
help in areas that can be frustrating when
writing plain JavaScript
JavaScript Best Practices
• Don’t forget var keyword when assigning a
variable’s value for the first time.
Example: name='Javascript'; // Bad Practice
var name='JavaScript'; // // GoodPractice

• Use === instead of ==


Example: if(name=='Javascript') // Bad Practice
if(name==='Javascript') // Good Practice

• Use Semicolons for line termination.


Example:
firstName = 'Sultan' // Bad Practices
lastName = 'Khan' // Bad Practices

firstName = 'Sultan'; // Good Practices


lastName = 'Khan'; // Good Practices
•Avoid these JavaScript’s Keywords When Creating
Custom Identifiers

break ,case, catch, continue, default, delete, do, else, finally, for, function,
if, in, instanceof, new, return, switch, this, throw, try, typeof, var, void, while,
With

•Avoid the use of eval() or the Function constructor

Use of eval or the Function constructor are expensive operations as each time they
are called script engine must convert source code to executable code.

var func1 = new Function(functionCode);


var func2 = eval(functionCode)

•Don’t Change a Variable’s Type After Initial Declaration


var my_variable = "This is a String";
my_variable = 50;
• Make Multi-Line Comments Readable, But Simple
/*
* This is a multi-line comment ...
* cont'd...
* cont'd...
* cont'd...
* cont'd...
*/

• Verify the argument before passing it to isFinite()


isFinite(0/0) ; // false
isFinite("foo"); // false
isFinite("10"); // true
isFinite(10); // true
isFinite(undefined); // false
isFinite(); // false
• Avoid using for-in loop for arrays
var sum = 0;
for (var i in arrayNumbers) {
sum += arrayNumbers[i];
}
var sum = 0;
for (var i = 0, len = arrayNumbers.length; i < len; i++) {
sum += arrayNumbers[i];
}
• Pass functions, not strings, to setTimeout()
and setInterval()
setInterval('doSomethingPeriodically()', 1000);
setTimeout('doSomethingAfterFiveSeconds()', 5000);

setInterval(doSomethingPeriodically, 1000);
setTimeout(doSomethingAfterFiveSeconds, 5000);
• Use a switch/case statement instead of a series of if/else
Using switch/case is faster when there are more than 2 cases, and it is more
elegant (better organized code). Avoid using it when you have more than
10 cases.

• Avoid using try-catch-finally inside a loop

var object = ['foo', 'bar'], i;


ar object = ['foo', 'bar'], i; try {
for (i = 0, len = object.length; i <len; i+ for (i = 0, len = object.length; i <len;
+) {
try { i++) {
// do something that throws an // do something that throws an
exception
} exception
catch (e) { }
// handle exception
}
}
} catch (e) {
// handle exception
}
• Instead of reading the length of an array at every
iteration, you should get it only once.

for (var i = 0; i < value.length; i += 1) {


console.log(value[i]);}

for (var i = 0, iCnt = haystack.length; i < iCnt; i += 1) {


console.log(haystack[i]);}

• You can concatenate strings in many ways, but most


efficient is Array.join()

var store = {'lemon': 'yellow', 'cherry': 'red'}


var str = "Lemons are " + store.lemon + ", tomatos are" + store.cherry;

var str = ["Lemons are ", store.lemon, ", tomatos are",


store.cherry].join("");
• Use a variable initialized with a Function Expression to
define a function within a block.
if (x) {
function foo() {}
}

if (x) {
var foo = function() {};
}
• No reason to use wrapper objects for primitive types,
plus they're dangerous.

var x = new Boolean(false); var x = Boolean(0);


if (x) { if (x) {
alert('hi'); // Shows 'hi'. alert('hi'); // This will never be alerted.
} }
• Always Use Closure
function foo(element, a, b) {
element.onclick = function() { /* uses a and b */ };
}

function foo(element, a, b) {
element.onclick = bar(a, b);
}

function bar(a, b) {
return function() { /* uses a and b */ };
}
• Do not use Multiline string literals
var myString = 'A rather long string of English text, an error message \
actually that just keeps going and going -- an error \
message to make the Energizer ';

var myString = 'A rather long string of English text, an error message ' +
'actually that just keeps going and going -- an error ' + 'message to make the
Energizer';
• For consistency single-quotes (') are preferred to
double-quotes ("). This is helpful when creating strings
that include HTML:

var msg = 'This is some HTML';

Don’t forget to use a code beautifier


when coding. Use JSLint and
minification (JSMin, for example)
before going live.
Best Practices
• Always load your jQuery framework from CDN
<script type="text/javascript" src="/js/jquery.js">
</script>

<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>

• Always Use Shorthand for $(document).ready()


$(document).ready(function() {
....
});

$(function() {
});
• Load jQuery locally when CDN fails
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

<script type="text/javascript">
if (typeof jQuery == 'undefined')
{
document.write('<script src="/js/jqeury.js"></script>');
}
</script>
• Always try to use ID as selector
$("#elmID");

• Use class selector with tags


$(".myCSSClass");

$(“div .myCSSClass”)
• Keep your selector simple, don't make it complex

$("body .main p#myID em");

$("p#myID em");

• Don't use your selector repeatedly.


$("#myID").css("color", "red");
$("#myID").css("font", "Arial");
$("#myID").text("Error occurred!");

$("p").css({ "color": "red", "font": "Arial"}).text("Error occurred!");


• when you are comparing empty elements try to follow
this
$(document).ready(function() {
if ($('#dvText').html().trim()) {
alert('Proceed as element is not empty.');
}
else
{
alert('Element is empty');
}
});
• Avoid jQuery.Post(), use jQuery.ajax()
$.post( url, [data], [callback], [type] )

$.ajax({url: "", success: function(result){


},error:function(result){});
• Cache jQuery Objects
$('#traffic_light input.on).bind('click', function(){...});
$('#traffic_light input.on).css('border', '3px dashed yellow');
$('#traffic_light input.on).css('background-color', 'orange');
$('#traffic_light input.on).fadeIn('slow');

var $active_light = $('#traffic_light input.on');


$active_light.bind('click', function(){...});
$active_light.css('border', '3px dashed yellow');
$active_light.css('background-color', 'orange');
$active_light.fadeIn('slow');

• Classes are Great


Use CSS classes whenever possible instead of inline CSS.
$("element").css({"color":"red","font-size:"20px"})
$("element").addClass("pstyle");
• jQuery's Chaining Feature
Chaining is a great feature in jQuery that allows you to chain method calls. Here is an
Example:
$
('sampleElement').removeClass('classToBeRemoved').addClass('classToBe
Added');

• Always use data method and avoid storing data inside


the DOM
$('#selector').attr('alt', 'your description.....');
$('#selector').data('alt', 'your description.....');
• Use find() rather than context

var divs = $('.testdiv', '#pageBody');


var divs = $('#pageBody').find('.testdiv');
var divs = $('#pageBody .testdiv');
• Write your own selectors
$.extend($.expr[':'], {
abovethefold: function(el) {
return $(el).offset().top < $(window).scrollTop() + $(window).height();
}
});
var nonVisibleElements = $('div:abovethefold'); // Select the elements

• Store jQuery results for later

App.hiddenDivs = $('div.hidden');
// later in your application:
App.hiddenDivs.find('span');
• Benchmark Your jQuery Code
Always benchmark your code and see which query is slower to replace it
// Shortcut to log data to the Firebug console
$.l($('div'));
// Get the UNIX timestamp
$.time();
// Log the execution time of a JS block to Firebug
$.lt();
$('div');
$.lt();
// Run a block of code in a for loop to test the execution time
$.bm("var divs = $('.testdiv', '#pageBody');"); // 2353 on Firebug

• best way to Using $this keyword

$('li').each(function() {
$(this).on('click', function() {
$(this).addClass('active');
});
});
$('li').each(function() {
var $this = $(this);
$this.on('click', function() {
$this.addClass('active');
});
});

• Avoid the universal selectors

// Slow
$('div.container > *');

// Faster
$('.container').children();
• Using filtering methods instead of pseudo selectors
$('.item:first')

$('.item').eq(0)

• Don't put all parameters in Ajax URL


$.ajax({
url: '/remote/url?param1=value1&param2=value2...'
}});

$.ajax({
url: '/remote/url',
data: {
param1: 'value1',
param2: 'value2'
}
});
• References

• http://tutorialzine.com/
• http://viralpatel.net/blogs/category/javascript/
• https://learn.jquery.com/
• http://www.sitepoint.com/javascript/jquery/

You might also like