2. What is Javascript & jQuery
JavaScript jQuery
Developers need to handle by writing
their own Javascript code.
Query is a multi-browser JavaScript library
designed to simplify the client-side
scripting of HTML.
If you use JavaScript, you need to write
you own scripting which may take time.
If you use Jquery, you need not to write
much scripting which already exists in
JQuery.
JavaScript is a language. Example: JQuery
like a foriegn language which is already
built by Javascript which is unknown to
you what kind of JS is written there, you
are just using it.
JQuery is a framework built with
JavaScript to help JavaScript programmers
who are doing common web tasks.
Example: But if you goto a country where
it is spoken, a guide can still help you
along, making your journey easier. jQuery
is one of many frameworks which provide
help in areas that can be frustrating when
writing plain JavaScript
3. • 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
JavaScript Best Practices
4. •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;
5. • 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
6. • 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);
7. • 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
ar object = ['foo', 'bar'], i;
for (i = 0, len = object.length; i <len; i+
+) {
try {
// do something that throws an
exception
}
catch (e) {
// handle exception
}
}
var object = ['foo', 'bar'], i;
try {
for (i = 0, len = object.length; i <len;
i++) {
// do something that throws an
exception
}
}
catch (e) {
// handle exception
}
8. • 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("");
9. • 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);
if (x) {
alert('hi'); // Shows 'hi'.
}
var x = Boolean(0);
if (x) {
alert('hi'); // This will never be alerted.
}
10. • 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';
11. • 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.
13. • 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() {
});
14. • 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”)
15. • 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!");
16. • 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){});
17. • 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");
18. • 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');
19. • 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');
20. • 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');
});
});