SlideShare uma empresa Scribd logo
1 de 23
Best Code Practices & Tips and Tricks
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
• 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
•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
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
}
• 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);
if (x) {
alert('hi'); // Shows 'hi'.
}
var x = Boolean(0);
if (x) {
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/

Mais conteúdo relacionado

Mais procurados

JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101ygv2000
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To ClosureRobert Nyman
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsRan Mizrahi
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design PatternsAddy Osmani
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJamshid Hashimi
 
From YUI3 to K2
From YUI3 to K2From YUI3 to K2
From YUI3 to K2kaven yan
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Domkaven yan
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorialDoeun KOCH
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overviewjeresig
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module PatternsNicholas Jansma
 
JavaScript Best Pratices
JavaScript Best PraticesJavaScript Best Pratices
JavaScript Best PraticesChengHui Weng
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascriptmpnkhan
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design PrinciplesJon Kruger
 
JavaScript Misunderstood
JavaScript MisunderstoodJavaScript Misunderstood
JavaScript MisunderstoodBhavya Siddappa
 
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)raja kvk
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptStoyan Stefanov
 

Mais procurados (20)

JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
 
Java script
Java scriptJava script
Java script
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
 
From YUI3 to K2
From YUI3 to K2From YUI3 to K2
From YUI3 to K2
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
Java script tutorial
Java script tutorialJava script tutorial
Java script tutorial
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overview
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
JavaScript Best Pratices
JavaScript Best PraticesJavaScript Best Pratices
JavaScript Best Pratices
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascript
 
Javascript
JavascriptJavascript
Javascript
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design Principles
 
JavaScript Misunderstood
JavaScript MisunderstoodJavaScript Misunderstood
JavaScript Misunderstood
 
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
 
Javascript 101
Javascript 101Javascript 101
Javascript 101
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
 

Semelhante a Javascript and Jquery Best practices

gdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptxgdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptxsandeshshahapur
 
10 Groovy Little JavaScript Tips
10 Groovy Little JavaScript Tips10 Groovy Little JavaScript Tips
10 Groovy Little JavaScript TipsTroy Miles
 
BITM3730 10-17.pptx
BITM3730 10-17.pptxBITM3730 10-17.pptx
BITM3730 10-17.pptxMattMarino13
 
BITM3730Week6.pptx
BITM3730Week6.pptxBITM3730Week6.pptx
BITM3730Week6.pptxMattMarino13
 
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLê Thưởng
 
BITM3730 10-4.pptx
BITM3730 10-4.pptxBITM3730 10-4.pptx
BITM3730 10-4.pptxMattMarino13
 
BITM3730 10-3.pptx
BITM3730 10-3.pptxBITM3730 10-3.pptx
BITM3730 10-3.pptxMattMarino13
 
Javascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & AngularJavascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & AngularErik Guzman
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScriptMarlon Jamera
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformationLars Marius Garshol
 
React Native Evening
React Native EveningReact Native Evening
React Native EveningTroy Miles
 

Semelhante a Javascript and Jquery Best practices (20)

gdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptxgdscWorkShopJavascriptintroductions.pptx
gdscWorkShopJavascriptintroductions.pptx
 
Java script
Java scriptJava script
Java script
 
10 Groovy Little JavaScript Tips
10 Groovy Little JavaScript Tips10 Groovy Little JavaScript Tips
10 Groovy Little JavaScript Tips
 
BITM3730 10-17.pptx
BITM3730 10-17.pptxBITM3730 10-17.pptx
BITM3730 10-17.pptx
 
BITM3730Week6.pptx
BITM3730Week6.pptxBITM3730Week6.pptx
BITM3730Week6.pptx
 
UNIT 3.ppt
UNIT 3.pptUNIT 3.ppt
UNIT 3.ppt
 
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdf
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
BITM3730 10-4.pptx
BITM3730 10-4.pptxBITM3730 10-4.pptx
BITM3730 10-4.pptx
 
BITM3730 10-3.pptx
BITM3730 10-3.pptxBITM3730 10-3.pptx
BITM3730 10-3.pptx
 
Performance patterns
Performance patternsPerformance patterns
Performance patterns
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
Javascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & AngularJavascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & Angular
 
Jquery 1
Jquery 1Jquery 1
Jquery 1
 
Rails and security
Rails and securityRails and security
Rails and security
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformation
 
JavaScript_introduction_upload.pdf
JavaScript_introduction_upload.pdfJavaScript_introduction_upload.pdf
JavaScript_introduction_upload.pdf
 
React Native Evening
React Native EveningReact Native Evening
React Native Evening
 

Último

Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...masabamasaba
 

Último (20)

Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 

Javascript and Jquery Best practices

  • 1. Best Code Practices & Tips and Tricks
  • 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'); }); });
  • 21. $('li').each(function() { var $this = $(this); $this.on('click', function() { $this.addClass('active'); }); }); • Avoid the universal selectors // Slow $('div.container > *'); // Faster $('.container').children();
  • 22. • 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' } });
  • 23. • References • http://tutorialzine.com/ • http://viralpatel.net/blogs/category/javascript/ • https://learn.jquery.com/ • http://www.sitepoint.com/javascript/jquery/