SlideShare a Scribd company logo
1 of 52
Ten Useful 
JavaScript 
Tips & Best Practices
I Am 
Ankit Rastogi 
a passionate Learner 
Website : http://ankitrastogi.com
Stages of Learning 
Shuhari - first learn, then detach, and 
finally transcend 
Shu - “Obey” 
ha - “Detach” 
ri - “Separate”
1 
Method Chaining 
It is a technique for calling multiple functions on the 
same object consecutively. 
new Employee() 
.setName("Ankit") 
.setDesignation("Consultant") 
.setDepartment("Engineering") 
.save();
var Employee = function() { 
this.name = "Default Name"; 
this.designation = "Default Designation"; 
this.department = "Default Department"; 
}; 
Employee.prototype.setName = function(name) { 
this.name = name; 
return this; 
}; 
Employee.prototype.save = function() { 
console.log("Saving the Employee information in database"); 
return this; 
};
2 
Event Delegation 
Allows you to avoid adding event listeners to specific 
nodes; instead, the event listener is added to one 
parent. 
<ul id="parent-list"> 
<li id="post-1">Item 1</li> 
<li id="post-2">Item 2</li> 
. . . 
<li id="post-5oo">Item 500</li> 
</ul>
function getEventTarget(e) { 
e = e || window.event; 
return e.target || e.srcElement; 
} 
// Get the element, add a click listener... 
document.getElementById("parent-list").addEventListener("click", 
function(e) { 
var target = getEventTarget(e); 
// e.target is the clicked element! 
// If it was a list item 
if(target && target.nodeName == "LI") { 
// List item found! Output the ID! 
} 
});
3 
Debounce 
Postpone the passed function execution until after 
wait milliseconds have elapsed since the last time it 
was invoked. 
var lazyLayout = debounce(250, function() { 
// This code gets executed after 
// 250 ms have passed since the last 
// invoked time 
}); 
$(window).resize(lazyLayout);
function debounce(delay, callback) { 
2 
var timeout = null; 
return function () { 
// 
// if a timeout has been registered before then 
// cancel it so that we can setup a fresh timeout 
// 
if (timeout) { 
clearTimeout(timeout); 
} 
var context = this; 
var args = arguments; 
timeout = setTimeout(function () { 
callback.apply(context, args); 
timeout = null; 
}, delay); 
}; 
}
4 
Throttle 
Call the original function at most once per every wait 
milliseconds. 
var scrollHandler = throttle(250, function() { 
// This code gets executed after 
// 250 ms have passed. 
}); 
$(window).scroll(scrollHandler);
function throttle(delay, callback) { 
var previousCall = new Date().getTime(); 
return function() { 
var time = new Date().getTime(); 
// 
// if "delay" milliseconds have expired since 
// the previous call then propagate this call to 
// "callback" 
// 
if ((time - previousCall) >= delay) { 
previousCall = time; 
callback.apply(null, arguments); 
} 
}; 
}
5 
Method Queue Pattern 
Popularized by Google Analytics tracking code. 
Also known as asynchronous function queuing. 
// onClick event is tracked by google analytics 
<a href="#" onClick="_gaq.push(['_trackEvent', 
'Videos', 'Play', 'Description of Video']);" 
>Play</a>
var _gaq = _gaq || []; 
_gaq.push(['_setAccount', 'UA-XXXXX-X']); 
_gaq.push(['_trackPageview']); 
(function() { 
var ga = document.createElement('script'); ga.type = 
'text/javascript'; 
ga.async = true; 
ga.src = ('https:' == document.location.protocol ? 'https: 
//ssl' : 'http://www') + '.google-analytics.com/ga.js'; 
var s = document.getElementsByTagName('script')[0]; s. 
parentNode.insertBefore(ga, s); 
})();
// get the existing _gaq array 
var _old_gaq = window._gaq; 
// create a new _gaq object 
window._gaq = new GoogleAnalyticsQueue(); 
// execute all of the queued up events - apply() turns 
// the array entries into individual arguments 
window._gaq.push.apply(window._gaq, _old_gaq); 
2
var GoogleAnalyticsQueue = function () { 
this.push = function () { 
for (var i = 0; i < arguments.length; i++) try { 
2 
if (typeof arguments[i] === "function") arguments[i](); 
else { 
// get tracker function from arguments[i][0] 
// get tracker function arguments from 
// arguments[i].slice(1) 
// call it! 
// trackers[arguments[i][0]] 
// .apply(trackers,arguments[i].slice(1)); 
} 
} catch (e) {} 
} 
// more code here… 
};
6 
Plus Operator 
Convert anything to a number. 
// Quick hex to dec conversion: 
+"0xFF"; // -> 255 
// Get a timestamp for now, the equivalent of `new 
Date().getTime()`: 
+new Date(); 
// for shortening something like if (someVar === 
null) someVar = 0; 
+null; // -> 0;
// Safer parsing than parseFloat()/parseInt() 
parseInt("1,000"); // -> 1, not 1000 
+"1,000"; // -> NaN, much better for testing user input 
parseInt("010"); // -> 8, because of the octal literal prefix 
+"010"; // -> 10, `Number()` doesn't parse octal 
literals 
2 
// Boolean to integer 
+true; // -> 1; 
+false; // -> 0; 
// Other useful tidbits: 
+"1e10"; // -> 10000000000 
+"1e-4"; // -> 0.0001 
+"-12"; // -> -12
var rnd = { 
"valueOf": 
function () { return Math.floor(Math.random()*1000); } 
2 
}; 
+rnd; // -> 442; 
+rnd; // -> 727; 
+rnd; // -> 718;
7 
Shorten Scope Chains 
Global Namespace is crowded. 
Javascript Look Up first in local than global. 
Use local variables to cache global one. 
var a = function(){ 
var doc = document, 
blah = doc.getElementById('myID'), 
blah2 = doc.getElementById('myID2'); 
}
2 
var aGlobalVar = 1; 
function doSomething(val) { 
var i = 1000, agv = aGlobalVar; 
while (i--) { 
agv += val; 
}; 
aGlobalVar = agv; 
}; 
doSomething(10);
8 
Memoization 
It is a programming technique which attempts to 
increase a function’s performance by caching its 
previously computed results. 
var costlyOperation = function(a){ 
// Time consuming operations 
}; 
memoizedOperation = memoize(costlyOperation); 
memoizedOperation(a);
function memoize( f ) { 
return function () { 
2 
var args = Array.prototype.slice.call(arguments); 
//we've confirmed this isn't really influencing 
//speed positively 
f.memoize = f.memoize || {}; 
//this is the section we're interested in 
return (args in f.memoize)? f.memo[args] : 
f.memoize[args] = f.apply(this, args); 
}; 
}
9 
Lazy JS Parsing 
Minimizing JavaScript parse time. 
Increase performance especially in mobile. 
<html> 
... 
<script id="lazy"> 
/* 
JavaScript of lazy module 
*/ 
</script>
<script> 
function lazyLoad() { 
2 
var lazyElement = document.getElementById('lazy'); 
var lazyElementBody = lazyElement.innerHTML; 
var jsCode = stripOutCommentBlock(lazyElementBody); 
eval(jsCode); 
} 
</script> 
<div onclick=lazyLoad()> Lazy Load </div> 
</html>
10 
DOM Manipulation
Identify the problem? 
function updateAllAnchors(element, anchorClass) { 
var anchors = element.getElementsByTagName('a'); 
for (var i = 0, length = anchors.length; i < length; i ++) { 
anchors[i].className = anchorClass; 
} 
}
function removeToInsertLater(element) { 
2 
var parentNode = element.parentNode; 
var nextSibling = element.nextSibling; 
parentNode.removeChild(element); 
return function() { 
if (nextSibling) { 
parentNode.insertBefore(element, nextSibling); 
} else { 
parentNode.appendChild(element); 
} 
}; 
} 
Solution
function updateAllAnchors(element, anchorClass) { 
var insertFunction = removeToInsertLater(element); 
var anchors = element.getElementsByTagName('a'); 
for (var i = 0, length = anchors.length; i < length; i ++) { 
2 
anchors[i].className = anchorClass; 
} 
insertFunction(); 
} 
Solution
Identify the problem? 
function addAnchors(element) { 
var anchor; 
for (var i = 0; i < 10; i ++) { 
anchor = document.createElement('a'); 
anchor.innerHTML = 'test'; 
element.appendChild(anchor); 
} 
}
function addAnchors(element) { 
var anchor, fragment = document.createDocumentFragment(); 
for (var i = 0; i < 10; i ++) { 
2 
anchor = document.createElement('a'); 
anchor.innerHTML = 'test'; 
fragment.appendChild(anchor); 
} 
element.appendChild(fragment); 
} 
Solution
Bonus 
Identify the problem
2 
Identify the problem 
baz.Bar = function() { 
// constructor body 
this.foo = function() { 
// method body 
}; 
}
2 
baz.Bar = function() { 
// constructor body 
} 
baz.Bar.prototype.foo = function() { 
// method body 
}; 
Solution
2 
Identify the problem 
foo.Bar = function() { 
this.prop1_ = 4; 
this.prop2_ = true; 
this.prop3_ = []; 
this.prop4_ = 'blah'; 
};
2 
Solution 
foo.Bar = function() { 
this.prop3_ = []; 
}; 
foo.Bar.prototype.prop1_ = 4; 
foo.Bar.prototype.prop2_ = true; 
foo.Bar.prototype.prop4_ = 'blah';
2 
function setupAlertTimeout() { 
var msg = 'Message to alert'; 
window.setTimeout(function() { 
alert(msg); 
}, 100); 
} 
Identify the problem
2 
function setupAlertTimeout() { 
window.setTimeout(function() { 
var msg = 'Message to alert'; 
alert(msg); 
}, 100); 
} 
Solution?
2 
function alertMsg() { 
var msg = 'Message to alert'; 
alert(msg); 
} 
function setupAlertTimeout() { 
window.setTimeout(alertMsg, 100); 
} 
Solution
2 
var divs = document.getElementsByTagName('div'); 
for (var i=0; i < divs.length; i++ ) { 
var div = document.createElement("div"); 
document.appendChild(div); 
} 
Identify the problem
function array(items) { 
2 
try { 
return Array.prototype.concat.call(items); 
} catch (ex) { 
var i = 0, 
len = items.length, 
result = Array(len); 
while (i < len) { 
result[i] = items[i]; 
i++; 
} 
return result; 
} 
} 
Solution
2var divs = array( document.getElementsByTagName('div') 
); 
for (var i=0; i < divs.length; i++ ) { 
var div = document.createElement("div"); 
document.appendChild(div); 
} 
Solution
Bonus 
Angular Js
Cache Factory 
var cache = $cacheFactory('cacheId'); 
expect($cacheFactory.get('cacheId')).toBe(cache); 
expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined(); 
2 
cache.put("key", "value"); 
cache.put("another key", "another value"); 
// We've specified no options on creation 
expect(cache.info()).toEqual({id: 'cacheId', size: 2});
ng-repeat with track by 
<ul class="tasks"> 
<li ng-repeat="task in tasks" ng-class="{done: task. 
2 
done}"> 
{{task.id}}: {{task.title}} 
</li> 
</ul> 
$scope.tasks = newTasksFromTheServer;
ng-repeat with track by 
2 ng-repeat="task in tasks track by task.id"
$parse, $interpolate, $compile 
2 var imgHtml = '<img ng-src="/path/{{name}}.{{extension}}">' 
$scope.name = 'image'; 
$scope.extension = 'jpg';
$parse, $interpolate, $compile 
$parse is concerned with individual expressions only (name, extension). 
It is a read-write service. 
2 
$interpolate is read only and is concerned with strings containing 
multiple expressions (/path/{{name}}.{{extension}}) 
$compile is at the heart of AngularJS machinery and can turn HTML 
strings (with directives and interpolation expressions) into live DOM.
Q & A
References : 
● http://davidwalsh.name/event-delegate 
● http://underscorejs.org/ 
● http://blogorama.nerdworks.in/javascriptfunctionthrottlingan/ 
● http://mrcoles.com/blog/google-analytics-asynchronous-tracking-how-it-work/ 
● http://stackoverflow.com/questions/61088/hidden-features-of-javascript 
● http://archive.devwebpro.com/devwebpro-39-20030514OptimizingJavaScriptforExecutionSpeed.html 
● http://www.sitepoint.com/implementing-memoization-in-javascript/ 
● http://googlecode.blogspot.in/2009/09/gmail-for-mobile-html5-series-reducing.html 
● https://developers.google.com/speed/articles/javascript-dom 
● http://www.phpied.com/rendering-repaint-reflowrelayout-restyle/ 
● https://developers.google.com/speed/articles/optimizing-javascript 
● https://docs.angularjs.org/api/ng/service/$cacheFactory 
● http://www.codelord.net/2014/04/15/improving-ng-repeat-performance-with-track-by/ 
● http://stackoverflow.com/questions/17900588/what-is-the-difference-between-the-parse-interpolate-and-compile- 
services
Thank you

More Related Content

What's hot

Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Aaron Gustafson
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...go_oh
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascriptDoeun KOCH
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of JavascriptTarek Yehia
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testingVikas Thange
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101ygv2000
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptjnewmanux
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptStoyan Stefanov
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design PatternsPham Huy Tung
 
JavaScript Design Patterns
JavaScript Design PatternsJavaScript Design Patterns
JavaScript Design PatternsDerek Brown
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design PrinciplesJon Kruger
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design PatternsAddy Osmani
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRaimonds Simanovskis
 

What's hot (20)

Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
 
Headless Js Testing
Headless Js TestingHeadless Js Testing
Headless Js Testing
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
JavaScript Design Patterns
JavaScript Design PatternsJavaScript Design Patterns
JavaScript Design Patterns
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design Principles
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
 
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
 

Viewers also liked

Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practicesManav Gupta
 
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best PracticesJohannes Hoppe
 
JavaScript 從零開始
JavaScript 從零開始JavaScript 從零開始
JavaScript 從零開始Adam Hung
 
使用 Visual Studio Code 建構 JavaScript 應用程式
使用 Visual Studio Code 建構 JavaScript 應用程式使用 Visual Studio Code 建構 JavaScript 應用程式
使用 Visual Studio Code 建構 JavaScript 應用程式Will Huang
 
Visual Studio Code 快速上手指南
Visual Studio Code 快速上手指南Visual Studio Code 快速上手指南
Visual Studio Code 快速上手指南Shengyou Fan
 
用JavaScript 實踐《軟體工程》的那些事兒!
用JavaScript  實踐《軟體工程》的那些事兒!用JavaScript  實踐《軟體工程》的那些事兒!
用JavaScript 實踐《軟體工程》的那些事兒!鍾誠 陳鍾誠
 

Viewers also liked (8)

Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
2013-02-21 - .NET UG Rhein-Neckar: JavaScript Best Practices
 
JavaScript 從零開始
JavaScript 從零開始JavaScript 從零開始
JavaScript 從零開始
 
使用 Visual Studio Code 建構 JavaScript 應用程式
使用 Visual Studio Code 建構 JavaScript 應用程式使用 Visual Studio Code 建構 JavaScript 應用程式
使用 Visual Studio Code 建構 JavaScript 應用程式
 
Visual Studio Code 快速上手指南
Visual Studio Code 快速上手指南Visual Studio Code 快速上手指南
Visual Studio Code 快速上手指南
 
Predictive Modelling
Predictive ModellingPredictive Modelling
Predictive Modelling
 
用JavaScript 實踐《軟體工程》的那些事兒!
用JavaScript  實踐《軟體工程》的那些事兒!用JavaScript  實踐《軟體工程》的那些事兒!
用JavaScript 實踐《軟體工程》的那些事兒!
 

Similar to Ten useful JavaScript tips & best practices

Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3Simon Su
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ EtsyNishan Subedi
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_functiontimotheeg
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScriptAndrew Dupont
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScriptkvangork
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascriptkvangork
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best PracticesYekmer Simsek
 
JavaScript Proven Practises
JavaScript Proven PractisesJavaScript Proven Practises
JavaScript Proven PractisesRobert MacLean
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleThierry Wasylczenko
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretssmueller_sandsmedia
 
Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Tsuyoshi Yamamoto
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsJarod Ferguson
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptSeok-joon Yun
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: FunctionsAdam Crabtree
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery ApplicationsRebecca Murphey
 

Similar to Ten useful JavaScript tips & best practices (20)

Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_function
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
 
JavaScript Proven Practises
JavaScript Proven PractisesJavaScript Proven Practises
JavaScript Proven Practises
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察Jggug 2010 330 Grails 1.3 観察
Jggug 2010 330 Grails 1.3 観察
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
Pro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScriptPro typescript.ch03.Object Orientation in TypeScript
Pro typescript.ch03.Object Orientation in TypeScript
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
 

Recently uploaded

FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 

Recently uploaded (20)

FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 

Ten useful JavaScript tips & best practices

  • 1. Ten Useful JavaScript Tips & Best Practices
  • 2. I Am Ankit Rastogi a passionate Learner Website : http://ankitrastogi.com
  • 3. Stages of Learning Shuhari - first learn, then detach, and finally transcend Shu - “Obey” ha - “Detach” ri - “Separate”
  • 4. 1 Method Chaining It is a technique for calling multiple functions on the same object consecutively. new Employee() .setName("Ankit") .setDesignation("Consultant") .setDepartment("Engineering") .save();
  • 5. var Employee = function() { this.name = "Default Name"; this.designation = "Default Designation"; this.department = "Default Department"; }; Employee.prototype.setName = function(name) { this.name = name; return this; }; Employee.prototype.save = function() { console.log("Saving the Employee information in database"); return this; };
  • 6. 2 Event Delegation Allows you to avoid adding event listeners to specific nodes; instead, the event listener is added to one parent. <ul id="parent-list"> <li id="post-1">Item 1</li> <li id="post-2">Item 2</li> . . . <li id="post-5oo">Item 500</li> </ul>
  • 7. function getEventTarget(e) { e = e || window.event; return e.target || e.srcElement; } // Get the element, add a click listener... document.getElementById("parent-list").addEventListener("click", function(e) { var target = getEventTarget(e); // e.target is the clicked element! // If it was a list item if(target && target.nodeName == "LI") { // List item found! Output the ID! } });
  • 8. 3 Debounce Postpone the passed function execution until after wait milliseconds have elapsed since the last time it was invoked. var lazyLayout = debounce(250, function() { // This code gets executed after // 250 ms have passed since the last // invoked time }); $(window).resize(lazyLayout);
  • 9. function debounce(delay, callback) { 2 var timeout = null; return function () { // // if a timeout has been registered before then // cancel it so that we can setup a fresh timeout // if (timeout) { clearTimeout(timeout); } var context = this; var args = arguments; timeout = setTimeout(function () { callback.apply(context, args); timeout = null; }, delay); }; }
  • 10. 4 Throttle Call the original function at most once per every wait milliseconds. var scrollHandler = throttle(250, function() { // This code gets executed after // 250 ms have passed. }); $(window).scroll(scrollHandler);
  • 11. function throttle(delay, callback) { var previousCall = new Date().getTime(); return function() { var time = new Date().getTime(); // // if "delay" milliseconds have expired since // the previous call then propagate this call to // "callback" // if ((time - previousCall) >= delay) { previousCall = time; callback.apply(null, arguments); } }; }
  • 12. 5 Method Queue Pattern Popularized by Google Analytics tracking code. Also known as asynchronous function queuing. // onClick event is tracked by google analytics <a href="#" onClick="_gaq.push(['_trackEvent', 'Videos', 'Play', 'Description of Video']);" >Play</a>
  • 13. var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-XXXXX-X']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https: //ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s. parentNode.insertBefore(ga, s); })();
  • 14. // get the existing _gaq array var _old_gaq = window._gaq; // create a new _gaq object window._gaq = new GoogleAnalyticsQueue(); // execute all of the queued up events - apply() turns // the array entries into individual arguments window._gaq.push.apply(window._gaq, _old_gaq); 2
  • 15. var GoogleAnalyticsQueue = function () { this.push = function () { for (var i = 0; i < arguments.length; i++) try { 2 if (typeof arguments[i] === "function") arguments[i](); else { // get tracker function from arguments[i][0] // get tracker function arguments from // arguments[i].slice(1) // call it! // trackers[arguments[i][0]] // .apply(trackers,arguments[i].slice(1)); } } catch (e) {} } // more code here… };
  • 16. 6 Plus Operator Convert anything to a number. // Quick hex to dec conversion: +"0xFF"; // -> 255 // Get a timestamp for now, the equivalent of `new Date().getTime()`: +new Date(); // for shortening something like if (someVar === null) someVar = 0; +null; // -> 0;
  • 17. // Safer parsing than parseFloat()/parseInt() parseInt("1,000"); // -> 1, not 1000 +"1,000"; // -> NaN, much better for testing user input parseInt("010"); // -> 8, because of the octal literal prefix +"010"; // -> 10, `Number()` doesn't parse octal literals 2 // Boolean to integer +true; // -> 1; +false; // -> 0; // Other useful tidbits: +"1e10"; // -> 10000000000 +"1e-4"; // -> 0.0001 +"-12"; // -> -12
  • 18. var rnd = { "valueOf": function () { return Math.floor(Math.random()*1000); } 2 }; +rnd; // -> 442; +rnd; // -> 727; +rnd; // -> 718;
  • 19. 7 Shorten Scope Chains Global Namespace is crowded. Javascript Look Up first in local than global. Use local variables to cache global one. var a = function(){ var doc = document, blah = doc.getElementById('myID'), blah2 = doc.getElementById('myID2'); }
  • 20. 2 var aGlobalVar = 1; function doSomething(val) { var i = 1000, agv = aGlobalVar; while (i--) { agv += val; }; aGlobalVar = agv; }; doSomething(10);
  • 21. 8 Memoization It is a programming technique which attempts to increase a function’s performance by caching its previously computed results. var costlyOperation = function(a){ // Time consuming operations }; memoizedOperation = memoize(costlyOperation); memoizedOperation(a);
  • 22. function memoize( f ) { return function () { 2 var args = Array.prototype.slice.call(arguments); //we've confirmed this isn't really influencing //speed positively f.memoize = f.memoize || {}; //this is the section we're interested in return (args in f.memoize)? f.memo[args] : f.memoize[args] = f.apply(this, args); }; }
  • 23. 9 Lazy JS Parsing Minimizing JavaScript parse time. Increase performance especially in mobile. <html> ... <script id="lazy"> /* JavaScript of lazy module */ </script>
  • 24. <script> function lazyLoad() { 2 var lazyElement = document.getElementById('lazy'); var lazyElementBody = lazyElement.innerHTML; var jsCode = stripOutCommentBlock(lazyElementBody); eval(jsCode); } </script> <div onclick=lazyLoad()> Lazy Load </div> </html>
  • 26. Identify the problem? function updateAllAnchors(element, anchorClass) { var anchors = element.getElementsByTagName('a'); for (var i = 0, length = anchors.length; i < length; i ++) { anchors[i].className = anchorClass; } }
  • 27. function removeToInsertLater(element) { 2 var parentNode = element.parentNode; var nextSibling = element.nextSibling; parentNode.removeChild(element); return function() { if (nextSibling) { parentNode.insertBefore(element, nextSibling); } else { parentNode.appendChild(element); } }; } Solution
  • 28. function updateAllAnchors(element, anchorClass) { var insertFunction = removeToInsertLater(element); var anchors = element.getElementsByTagName('a'); for (var i = 0, length = anchors.length; i < length; i ++) { 2 anchors[i].className = anchorClass; } insertFunction(); } Solution
  • 29. Identify the problem? function addAnchors(element) { var anchor; for (var i = 0; i < 10; i ++) { anchor = document.createElement('a'); anchor.innerHTML = 'test'; element.appendChild(anchor); } }
  • 30. function addAnchors(element) { var anchor, fragment = document.createDocumentFragment(); for (var i = 0; i < 10; i ++) { 2 anchor = document.createElement('a'); anchor.innerHTML = 'test'; fragment.appendChild(anchor); } element.appendChild(fragment); } Solution
  • 32. 2 Identify the problem baz.Bar = function() { // constructor body this.foo = function() { // method body }; }
  • 33. 2 baz.Bar = function() { // constructor body } baz.Bar.prototype.foo = function() { // method body }; Solution
  • 34. 2 Identify the problem foo.Bar = function() { this.prop1_ = 4; this.prop2_ = true; this.prop3_ = []; this.prop4_ = 'blah'; };
  • 35. 2 Solution foo.Bar = function() { this.prop3_ = []; }; foo.Bar.prototype.prop1_ = 4; foo.Bar.prototype.prop2_ = true; foo.Bar.prototype.prop4_ = 'blah';
  • 36. 2 function setupAlertTimeout() { var msg = 'Message to alert'; window.setTimeout(function() { alert(msg); }, 100); } Identify the problem
  • 37. 2 function setupAlertTimeout() { window.setTimeout(function() { var msg = 'Message to alert'; alert(msg); }, 100); } Solution?
  • 38. 2 function alertMsg() { var msg = 'Message to alert'; alert(msg); } function setupAlertTimeout() { window.setTimeout(alertMsg, 100); } Solution
  • 39. 2 var divs = document.getElementsByTagName('div'); for (var i=0; i < divs.length; i++ ) { var div = document.createElement("div"); document.appendChild(div); } Identify the problem
  • 40. function array(items) { 2 try { return Array.prototype.concat.call(items); } catch (ex) { var i = 0, len = items.length, result = Array(len); while (i < len) { result[i] = items[i]; i++; } return result; } } Solution
  • 41. 2var divs = array( document.getElementsByTagName('div') ); for (var i=0; i < divs.length; i++ ) { var div = document.createElement("div"); document.appendChild(div); } Solution
  • 43. Cache Factory var cache = $cacheFactory('cacheId'); expect($cacheFactory.get('cacheId')).toBe(cache); expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined(); 2 cache.put("key", "value"); cache.put("another key", "another value"); // We've specified no options on creation expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  • 44. ng-repeat with track by <ul class="tasks"> <li ng-repeat="task in tasks" ng-class="{done: task. 2 done}"> {{task.id}}: {{task.title}} </li> </ul> $scope.tasks = newTasksFromTheServer;
  • 45. ng-repeat with track by 2 ng-repeat="task in tasks track by task.id"
  • 46. $parse, $interpolate, $compile 2 var imgHtml = '<img ng-src="/path/{{name}}.{{extension}}">' $scope.name = 'image'; $scope.extension = 'jpg';
  • 47. $parse, $interpolate, $compile $parse is concerned with individual expressions only (name, extension). It is a read-write service. 2 $interpolate is read only and is concerned with strings containing multiple expressions (/path/{{name}}.{{extension}}) $compile is at the heart of AngularJS machinery and can turn HTML strings (with directives and interpolation expressions) into live DOM.
  • 48. Q & A
  • 49. References : ● http://davidwalsh.name/event-delegate ● http://underscorejs.org/ ● http://blogorama.nerdworks.in/javascriptfunctionthrottlingan/ ● http://mrcoles.com/blog/google-analytics-asynchronous-tracking-how-it-work/ ● http://stackoverflow.com/questions/61088/hidden-features-of-javascript ● http://archive.devwebpro.com/devwebpro-39-20030514OptimizingJavaScriptforExecutionSpeed.html ● http://www.sitepoint.com/implementing-memoization-in-javascript/ ● http://googlecode.blogspot.in/2009/09/gmail-for-mobile-html5-series-reducing.html ● https://developers.google.com/speed/articles/javascript-dom ● http://www.phpied.com/rendering-repaint-reflowrelayout-restyle/ ● https://developers.google.com/speed/articles/optimizing-javascript ● https://docs.angularjs.org/api/ng/service/$cacheFactory ● http://www.codelord.net/2014/04/15/improving-ng-repeat-performance-with-track-by/ ● http://stackoverflow.com/questions/17900588/what-is-the-difference-between-the-parse-interpolate-and-compile- services
  • 50.
  • 51.