SlideShare a Scribd company logo
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();

Recommended for you

Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript

Basic JavaScript Object Oriented Best Practices Library MVC Performance Debug Documentation Tools

javascriptmvctools
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing

This document provides an overview of basic JavaScript examples and concepts. It covers topics such as writing JavaScript code, variables, conditional statements, functions, loops, events, and error handling. For each topic, it provides short code snippets to demonstrate the concept. It concludes by referencing W3Schools as a resource and thanking the reader.

javascript introductionjavascriptjavascript basics
Headless Js Testing
Headless Js TestingHeadless Js Testing
Headless Js Testing

The document discusses generating headless JavaScript tests for validations. It describes problems with testing JavaScript across many views, models, and validations. It proposes using server-side and client-side validations, widgets, localization, and regular expressions to solve these problems. Tests are generated and executed using RSpec and a standalone JavaScript interpreter to test validations without a browser.

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);

Recommended for you

Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript

This document provides a summary of an introductory presentation on advanced JavaScript concepts including closures, prototypes, inheritance, and more. The presentation covers object literals and arrays, functions as objects, constructors and the this keyword, prototypes and the prototype chain, classical and prototypal inheritance, scope, and closures. Examples are provided to demonstrate each concept.

javascriptprototypeconstructor
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript

This document provides an introduction to JavaScript including: - JavaScript is an object-oriented scripting language that is a dialect of ECMAScript. - It was originally designed to add interactivity to HTML pages through dynamic HTML, reacting to events, and data validation. - JavaScript is now heavily used in AJAX-based sites to asynchronously retrieve and display data without reloading pages. - The document discusses JavaScript compatibility issues and provides examples of basic JavaScript concepts like variables, comparisons, repetition, and popup boxes.

Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript

JavaScript is the programming language of the web. It can dynamically manipulate HTML content by changing element properties like innerHTML. Functions allow JavaScript code to run in response to events like button clicks or timeouts. JavaScript uses objects and prototypes to define reusable behaviors and properties for objects. It is an important language for web developers to learn alongside HTML and CSS.

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>

Recommended for you

JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101

This document provides an overview of JavaScript 101. It discusses: 1. The roots of JavaScript including its development by Brendan Eich at Netscape in 1995 to add interactivity to web pages. 2. Core concepts of JavaScript including the DOM, objects, prototype-oriented programming, functions, timing events, scopes, and closures. 3. Advanced topics like callbacks, events, AJAX, performance factors, security considerations, and popular extension libraries. The document provides examples of JavaScript code to illustrate key points and concepts. It aims to give readers foundational knowledge to understand the basics of JavaScript before exploring further advances.

front end developmentprogrammingfed
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript

An easy dive into asynchronous programming and how it works with JavaScript's event loop, queue, and multiple threads.

asynchronousprogrammingjavascript
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6

Generators in ECMAScript provide a way to write iterator functions using the yield keyword. This allows for writing functions that can be iterated over manually or used to create infinite streams. Generators also enable asynchronous programming using coroutines instead of callbacks. They allow for cooperative multitasking by starting multiple generator functions as "threads" that yield values in a nondeterministic order. Array comprehensions are also proposed as a shorthand for transforming arrays using generators.

modulesdmitry soshnikovrest
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;

Recommended for you

Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript

Slides from my "Object-oriented JavaScript" presentation at CSDN (China Software Developers Network), Beijing, December 2008

stoyannetworkdevelopers
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns

This document discusses several common JavaScript design patterns including Singleton, Factory, Module, Decorator, Command, and Observer patterns. It provides descriptions and code examples for each pattern. The Singleton pattern ensures a class only has one instance and provides a global access point. Factory patterns are used for object creation. The Module pattern provides private and public encapsulation for classes. The Decorator pattern attaches additional responsibilities to objects dynamically. The Command pattern encapsulates requests as objects, and the Observer pattern allows objects to watch other objects for changes.

javascriptdesign pattern
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics

The document provides an overview of JavaScript, covering what it is, its basics, functions, objects, prototypes, scope, asynchronous JavaScript, JSON, debugging tools, performance, events, error handling, and the future of JavaScript. It discusses that JavaScript is an object-oriented scripting language used in web pages that is not tied to specific browsers but makes use of the DOM, BOM, and ECMAScript standards. It also summarizes some of JavaScript's core features like functions, objects, prototypes, and more.

javascript
// 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);

Recommended for you

JavaScript Design Patterns
JavaScript Design PatternsJavaScript Design Patterns
JavaScript Design Patterns

Great design patterns are reusable, modular expressions of what’s going on in your code. They allow you to communicate to other developers simply by the way you code, in addition to being easily maintainable themselves. Put simply, patterns are the available tools in the developer’s toolbox. In this presentation, I review a few common patterns, their advantages/disadvantages, and how they can be implemented. The source for this presentation can be found here: https://github.com/derekbrown/designpatterns

javascriptobject-oriented programmingweb development
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design Principles

The document discusses object-oriented programming and design principles. It defines OOP as a programming paradigm based on classes and cooperating objects. It then discusses the SOLID principles of object-oriented design, which are guidelines for writing reusable, flexible and maintainable code. Specifically, it emphasizes that classes and methods should have a single responsibility, code should be open for extension but closed for modification, and software should be designed to be easy to test, change and add new features to.

Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1

In JS: CLASS &lt;=> Constructor FN new FN() => FN() { this } FN = CLASS (FN = FN, FN = DATA) Objects Prototype / __proto__ Inheritence Rewriting / Augmenting built in objects

oojsjava scriptinheritence
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>

Recommended for you

Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns

The document discusses the module pattern, a design pattern for creating reusable components in JavaScript. It describes how the module pattern allows simulating privacy by wrapping code in immediately invoked function expressions (IIFEs) and returning objects instead of functions. This creates a private scope that is not accessible globally while exposing public APIs. Several examples are given of how different libraries like Dojo, jQuery, YUI, and ExtJS implement the module pattern.

scalablejavascriptdesign 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

The document discusses using CoffeeScript to write JavaScript code in a more Ruby-like style. It provides examples of CoffeeScript code for functions, objects, classes, and other concepts. CoffeeScript allows JavaScript code to be written in a cleaner syntax that resembles Ruby. This helps address problems with JavaScript code appearing "ugly" and unfamiliar to developers experienced in Ruby. CoffeeScript transpires to regular JavaScript, enabling the Ruby-like code to run in browsers.

railswaycon javascript coffeescript backbonejs jas
Javascript Best Practices
Javascript Best PracticesJavascript Best Practices
Javascript Best Practices

A presentation about tricks and best practice ideas of how to use JavaScript given in our office in India as part of an internal training.

webdevtricktipsbestpractices
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

Recommended for you

Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices

This document provides best practices for writing JavaScript code. It recommends using strict comparison operators (=== and !==), declaring variables with 'var' to avoid globals, adding comments with /* */, using object literals for configuration, validating external data, optimizing loops, and using dot and bracket notation wisely based on property visibility. Braces {} should be used to clearly delimit blocks. Variable types should not be changed after declaration and shortcuts like conditionals (?:) can optimize code.

best practicejavascriptui
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

The document provides JavaScript best practices focusing on code quality, avoiding antipatterns like implied globals and eval, and recommendations for style like indentation and naming conventions. It also discusses testing with Jasmine including writing tests, making them pass, refactoring code, and repeating the test-driven development process. Modular code organization techniques like revealing module pattern and event publishing are also covered.

bestpracticesbddhtml5
JavaScript 從零開始
JavaScript 從零開始JavaScript 從零開始
JavaScript 從零開始

讀書分享會簡報

javascript
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 
}; 
}

Recommended for you

使用 Visual Studio Code 建構 JavaScript 應用程式
使用 Visual Studio Code 建構 JavaScript 應用程式使用 Visual Studio Code 建構 JavaScript 應用程式
使用 Visual Studio Code 建構 JavaScript 應用程式

這份是 Will 保哥在 JSDC.tw 2015 的演講簡報,介紹 Visual Studio Code 的基本架構與使用方式,並現場展示如何有效率的使用 Visual Studio Code 開發 Node.js 與 AngularJS 應用程式。

githubmacnode.js
Visual Studio Code 快速上手指南
Visual Studio Code 快速上手指南Visual Studio Code 快速上手指南
Visual Studio Code 快速上手指南

於 2016/5/28 在 Laravel 台灣 高雄社群小聚所分享的 Lightning Talk 內容,討論如何使用 Visual Studio Code 做為開發 PHP 專案的工具。

visual studio codedemophp
Predictive Modelling
Predictive ModellingPredictive Modelling
Predictive Modelling

Predictive modeling is a process used in predictive analytics to create statistical models that can forecast future outcomes based on historical data. Predictive modeling uses techniques from data mining, statistics, and machine learning to analyze current data to make predictions. The predictive modeling process involves collecting data, creating a model, testing and validating the model, and evaluating the model's performance. Predictive models are commonly used to predict customer behavior, risk levels, product performance, and more. Industries like retail, healthcare, finance, and telecommunications frequently use predictive modeling techniques.

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

Recommended for you

用JavaScript 實踐《軟體工程》的那些事兒!
用JavaScript  實踐《軟體工程》的那些事兒!用JavaScript  實踐《軟體工程》的那些事兒!
用JavaScript 實踐《軟體工程》的那些事兒!

十分鐘系列

Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript

The document discusses techniques for writing clean JavaScript code. It provides examples of code smells and improvements to address issues like attaching events from the outside, separating selection from logic, shallow scope, overwriting default behavior, and separating logic from views. The document advocates for practices like modularizing functions, separating DOM manipulation from models, and creating model objects to represent DOM elements rather than directly manipulating the DOM. It encourages learning clean JavaScript techniques to write better structured and more maintainable code.

javascript
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3

The document discusses Google App Engine task queues and cron jobs. It provides examples of creating and using default and named push queues, as well as pull queues. It explains how to add tasks, lease tasks from pull queues, and delete tasks. It also covers using task queues within transactions. Additionally, it demonstrates configuring and using cron jobs to schedule recurring tasks.

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

Recommended for you

Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript

This document provides examples and explanations of JavaScript concepts including objects and arrays, functions and contexts, closures, inheritance, namespaces and scope, module patterns, and dispatching. It demonstrates creating and manipulating objects and arrays, defining functions, using closures, implementing inheritance with prototypes and Object.create, creating namespaces, revealing and constructor module patterns, and a publisher/subscriber dispatching example.

inheritancemixinfunction
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries

The document discusses secrets and techniques for JavaScript libraries. It covers topics like the JavaScript language, cross-browser code, events, DOM traversal, styles, animations, distribution, and HTML insertion. It provides examples and explanations of techniques for class creation, timers, options, subclassing, custom events, selector internals, computed styles, and dimension calculations.

Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy

These are slides to my presentation on Virtual Madness - the virtual machine management platform at Etsy.

javascriptetsymarionette
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;

Recommended for you

JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring

This document discusses refactoring code to improve its design without changing external behavior. It notes that refactoring involves making small, incremental changes rather than large "big bang" refactorings. Code smells that may indicate a need for refactoring include duplication, long methods, complex conditional logic, speculative code, and overuse of comments. Techniques discussed include extracting methods, removing duplication, using meaningful names, removing temporary variables, and applying polymorphism. The document emphasizes that refactoring is an investment that makes future changes easier and helps avoid bugs, and encourages learning from other programming communities.

refactoringjavascript
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_function

The document discusses JavaScript functions and closures. It explains that functions are first-class objects that can be assigned to variables and passed as arguments. Closures allow inner functions to access variables in an outer function's scope even after it has returned. This can be used to emulate private variables or classes. The document provides many examples demonstrating functions, scopes, closures, recursion, and other JavaScript concepts.

Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript

Is your web app drowning in a sea of JavaScript? Has your client-side codebase grown from "a snippet here and there" to "more JavaScript than HTML"? Do you find yourself writing one-off snippets instead of generalized components? You're not the only one. Learn about a handful of strategies you can use to keep your JavaScript codebase lean, modular, and flexible. We'll cover all the major pain points — MVC, templates, persisting state, namespacing, graceful error handling, client/server communication, and separation of concerns. And we'll cover how to do all this incrementally so that you don't have to redo everything from scratch.

javascriptmixarchitecture
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

Recommended for you

Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript

The document discusses object-oriented programming concepts in JavaScript. It begins with an overview of how everything in JavaScript is an object, even functions, and how objects have prototypes. It then provides examples of using constructor functions, prototype inheritance, and the extend method to create base classes and subclasses. Config objects and model-view design patterns are also demonstrated. The examples show how to build classes for containers, limited containers, query controllers, and adding map and view capabilities to queries. Resources for further learning are provided at the end.

oojsdevsummit
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript

Object-Oriented JavaScript presentation given at the 2010 ESRI Developer Summit. Code and slides are also available at http://github.com/kvangork/OOJS-Presentation Find me on twitter @kvangork or my blog http://prng.vangorkom.org

oojsdevsummit
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices

This document provides an overview of key Android development concepts and techniques. It discusses fragments, the support library, dependency injection, image caching, threading and AsyncTask, notifications, supporting multiple screens, and optimizing ListView performance. The document also recommends several popular Android libraries and open source apps that demonstrate best practices.

androidjava
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
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
Thank you

Recommended for you

JavaScript Proven Practises
JavaScript Proven PractisesJavaScript Proven Practises
JavaScript Proven Practises

This document discusses proven JavaScript best practices for writing better code. It covers topics like always using var to declare variables, avoiding eval(), using object literals instead of the Object constructor, preferring === over ==, ending statements with semicolons, and turning on strict mode. Each topic is demonstrated with examples of bad code and how to fix it. The document aims to help programmers structure their code properly and avoid common pitfalls in JavaScript.

javascriptproven practise
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

JavaFX 8 est disponible depuis mars 2014 et apporte son lot de nouveautés. Gradle est en version 2 depuis juillet 2014. Deux technologies plus que prometteuses: JavaFX donne un coup de jeune au développement d’applications desktop en Java en apportant un navigateur web intégré, le support des WebSockets, de la 3D, et bien d’autres. Gradle est l’outil de d’automatisation de build à la mode, apportant de superbes possibilités par rapport rapport à maven, outil vieillissant, grâce à l’engouement de la communauté vis à vis de cet outil mais aussi par le fait de la technologie utilisée en son sein: groovy. Venez découvrir comment il est possible de réaliser rapidement une application à la mode en JavaFX avec un outil à la mode également. Bref venez à une session trendy.

bindinggradlejavafx
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

This document contains a summary of jQuery secrets presented by Bastian Feder. It discusses various techniques including saving and removing state from DOM elements using jQuery.data() and jQuery.removeData(), extending jQuery functionality through plugins, and customizing AJAX requests and event handling. The presentation provides code examples for working with jQuery's data storage methods, namespaces, promises/deferreds, global AJAX settings, and extending jQuery.

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 javascript
Doeun KOCH
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
Tarek Yehia
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
Vikas Thange
 
Headless Js Testing
Headless Js TestingHeadless Js Testing
Headless Js Testing
Brian Moschel
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
Stoyan Stefanov
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
Jussi Pohjolainen
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
Anjan Banda
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
ygv2000
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
jnewmanux
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
Stoyan Stefanov
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
Pham Huy Tung
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
Mats Bryntse
 
JavaScript Design Patterns
JavaScript Design PatternsJavaScript Design Patterns
JavaScript Design Patterns
Derek Brown
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design Principles
Jon Kruger
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
Rodica Dada
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
Addy 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 Jasmine
Raimonds 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 Practices
Christian Heilmann
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
Manav 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 Practices
Johannes 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
 
Predictive Modelling
Predictive ModellingPredictive Modelling
Predictive Modelling
Rajib Kumar De
 
用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

Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
Ryunosuke SATO
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3
Simon Su
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
Giovanni Scerra ☃
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
jeresig
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
Nishan Subedi
 
JavaScript Refactoring
JavaScript RefactoringJavaScript Refactoring
JavaScript Refactoring
Krzysztof Szafranek
 
The mighty js_function
The mighty js_functionThe mighty js_function
The mighty js_function
timotheeg
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
Andrew Dupont
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
kvangork
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
kvangork
 
Android Best Practices
Android Best PracticesAndroid Best Practices
Android Best Practices
Yekmer Simsek
 
JavaScript Proven Practises
JavaScript Proven PractisesJavaScript Proven Practises
JavaScript Proven Practises
Robert 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 gradle
Thierry 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 Secrets
smueller_sandsmedia
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
Bastian Feder
 
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.js
Jarod 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 TypeScript
Seok-joon Yun
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
Adam Crabtree
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
Rebecca 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

7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf
Enterprise Wired
 
20240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 202420240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 2024
Matthew Sinclair
 
WPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide DeckWPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide Deck
Lidia A.
 
Coordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar SlidesCoordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar Slides
Safe Software
 
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdfPigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions
 
What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024
Stephanie Beckett
 
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - MydbopsScaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Mydbops
 
Measuring the Impact of Network Latency at Twitter
Measuring the Impact of Network Latency at TwitterMeasuring the Impact of Network Latency at Twitter
Measuring the Impact of Network Latency at Twitter
ScyllaDB
 
Best Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdfBest Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdf
Tatiana Al-Chueyr
 
Quality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of TimeQuality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of Time
Aurora Consulting
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
Neo4j
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
Adam Dunkels
 
20240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 202420240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 2024
Matthew Sinclair
 
The Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive ComputingThe Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive Computing
Larry Smarr
 
Choose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presenceChoose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presence
rajancomputerfbd
 
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
Andrey Yasko
 
The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses
Larry Smarr
 
Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024
BookNet Canada
 
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALLBLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
Liveplex
 
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdfWhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
ArgaBisma
 

Recently uploaded (20)

7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf7 Most Powerful Solar Storms in the History of Earth.pdf
7 Most Powerful Solar Storms in the History of Earth.pdf
 
20240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 202420240704 QFM023 Engineering Leadership Reading List June 2024
20240704 QFM023 Engineering Leadership Reading List June 2024
 
WPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide DeckWPRiders Company Presentation Slide Deck
WPRiders Company Presentation Slide Deck
 
Coordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar SlidesCoordinate Systems in FME 101 - Webinar Slides
Coordinate Systems in FME 101 - Webinar Slides
 
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdfPigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdf
 
What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024What’s New in Teams Calling, Meetings and Devices May 2024
What’s New in Teams Calling, Meetings and Devices May 2024
 
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - MydbopsScaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
Scaling Connections in PostgreSQL Postgres Bangalore(PGBLR) Meetup-2 - Mydbops
 
Measuring the Impact of Network Latency at Twitter
Measuring the Impact of Network Latency at TwitterMeasuring the Impact of Network Latency at Twitter
Measuring the Impact of Network Latency at Twitter
 
Best Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdfBest Practices for Effectively Running dbt in Airflow.pdf
Best Practices for Effectively Running dbt in Airflow.pdf
 
Quality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of TimeQuality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of Time
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
 
20240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 202420240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 2024
 
The Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive ComputingThe Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive Computing
 
Choose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presenceChoose our Linux Web Hosting for a seamless and successful online presence
Choose our Linux Web Hosting for a seamless and successful online presence
 
Comparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdfComparison Table of DiskWarrior Alternatives.pdf
Comparison Table of DiskWarrior Alternatives.pdf
 
The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses
 
Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024
 
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALLBLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
BLOCKCHAIN FOR DUMMIES: GUIDEBOOK FOR ALL
 
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdfWhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
WhatsApp Image 2024-03-27 at 08.19.52_bfd93109.pdf
 

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