Java script best practices
Upcoming SlideShare
Loading in...5

Java script best practices



This presentation will help you to write better applications using JavaScript.

This presentation will help you to write better applications using JavaScript.



Total Views
Views on SlideShare
Embed Views



2 Embeds 101 94 7



Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

Java script best practices Java script best practices Presentation Transcript

  • “JavaScript: It is the language thatpeople use without bothering tolearn it first” Douglas Crockford
  • Coding
  • Use ‘===‘ instead of ‘==‘ However, when working with == and !=, you’ll run into issues when working with different types. In these cases, they’ll try to coerce the values, unsuccessfully.var x = 1, y = "1";console.log(x == y); //trueconsole.log(x === y); //falsevar x, y = null;console.log(x == y); //trueconsole.log(x === y); //falsevar x = ["", null, undefined];console.log(x == ",,"); //trueconsole.log(x === ",,"); //false
  • Eval is Bad Not only will this decrease your script’s performance substantially, but it also poses a huge security risk because it grants far too much power to the passed in text. Avoid it!var func = { method: function () { console.log(test); }};var whatToDo = "method";//Staticfunc.method();//Dynamic - DONT USEeval("func." + whatToDo + "()");//Dynamic - This is the right wayfunc[whatToDo]();
  • Don’t declare global variables “By reducing your global footprint to a single name, you significantly reduce the chance of bad interactions with other applications, widgets, or libraries.“ Douglas Crockfordvar DudeNameSpace = { name : Jeffrey, lastName : Way, doSomething : function() {...}}console.log(;
  • Always declare your variables using var If you declare a variable, without using "var", the variable always becomes GLOBAL.function test(){ name = "Jean"; //this is global}test();console.log(name) // “Jean”
  • Declare Variables on top variables should be declared on top of each function because of what is known as JavaScript Hoistingvar name = sarfraz;function test(){ console.log(name); var name = nawaz; console.log(name);}​test();​
  • Declare Variables Outside of the ForStatement When executing lengthy “for” statements, don’t make the engine work any harder than it must.var someArray = [1, 2, 3, 4];for (var i = 0; i < someArray.length; i++) { var container = "what"; console.log(i);}var names = [George,Ringo,Paul,John];for(var i=0,j=names.length;i<j;i++){ doSomeThingWith(names[i]);}
  • String Concatenation… Not easy to decide…var str = "";for (var i = 30000; i > 0; i--) { str += "String concatenation. ";}var str = "", sArr = [];for (var i = 30000; i > 0; i--) { sArr[i] = "String concatenation. ";}str = sArr.join("");var str = "";for (var i = 30000; i > 0; i--) { str = str.concat("String concatenation. ");}
  • String Concatenation (cont.)
  • Use [] Instead of New Array() "A common error in JavaScript programs is to use an object when an array is required or an array when an object is required. The rule is simple: when the property names are small sequential integers, you should use an array. Otherwise, use an object." Douglas Crockfordvar a = new Array();a[0] = "Joe";a[1] = Plumber;var a = [Joe,Plumber];
  • "For in" Statements When looping through items in an object, you might find that youll also retrieve method functions as well. In order to work around this, always wrap your code in an if statement which filters the information Don’t use “for in” to loop a array – slow performancefor(key in object) { if(object.hasOwnProperty(key) { ...then do something... }}
  • Use SetTimeOut instead SetInterval SetInterval will execute the code every [x] milliseconds no matter what.window.setInterval(function() { ajax_Call(); }, 500);setTimeout(function foo() { call_Ajax(y, function() { if (++y < 10) { setTimeout(foo, 100); } });}, 100);
  • Starting Curly Brace On The Same Line Thats one of the pitfalls of javascript: automatic semicolon insertionfunction myFunc(){ return; { name: sarfraz };}var f = myFunc();console.log(f); <--- ???
  • Dont use try-catch-finally inside performance-critical functions The try-catch-finally construct creates a new variable in the current scope at runtime each time the catch clause is executed where the caught exception object is assigned to a variable. Exception handling should be done at as high level in the script where it does not occur frequently, for example outside a loop. Or if possible, avoid try-catch-finally completelyvar object = [foo, bar], i;for (i = 0; i < object.length; i++) { try { // do something that throws an exception } catch (e) { // handle exception }}var object = [foo, bar], i;try { for (i = 0; i < object.length; i++) { // do something }} catch (e) { // handle exception}
  • new The new operator is required when calling a Constructor function. If new is omitted, the global object is clobbered by the constructor. There is no compile-time or run-time warning.​var x = function(){ alert(this); }var y = x(); //Window Objectvar z = new x(); //x Object
  • Debuggingconsole.log( firstVariable, secondVariable, xVariable);console.clear();
  • Function Declaration vs.Function Expression The function_expression form indicates that function are first-class objects, you can do anything with them like a variable. The only difference between them is that all function declarations are hoisted to the top of the scope which may matter in certain cases.function function_declaration() { …}​var function_expression = function() { ...}
  • Comment as much as needed but not more It might seem unnecessary at first, but trust me, you WANT to comment your code as best as possible. Comments don’t hurt anybody if you do them right. We’ll come back to that in the last point of this article, but let’s say that if your comments end up in the code that end users see then something is not going right.// Cycle through array and echo out each name.for(var i = 0, len = array.length; i < len; i++) { console.log(array[i]);}
  • Patterns
  • Cache values Notice how we must determine the length of the array for each iteration, and how we traverse the DOM to find the "container" element each time -- highly inefficient!for(var i = 0; i < someArray.length;i++) { …}var $myDiv = $("#myDiv");$myDiv.css("color","red");$myDiv.css("opacity",1);
  • Self-Executing Functions Rather than calling a function, its quite simple to make a function run automatically when a page loads, or a parent function is called. Simply wrap your function in parenthesis, and then append an additional set, which essentially calls the function.(function doSomething() { return { name: jeff, lastName: way };})();
  • Modularize — one function per task This is a general programming best practice — making sure that you create functions that fulfill one job at a time makes it easy for other developers to debug and change your code without having to scan through all the code to work out what code block performs what function.function addLink(text,url,parentElement){ var newLink = document.createElement(a); newLink.setAttribute(href,url); newLink.appendChild(document.createTextNode(text)); if( === menu){ newLink.className = menu-item; } if(url.indexOf(mailto:)!==-1){ newLink.className = mail; } parentElement.appendChild(newLink);}
  • Separate config datafunction validate(value) { if (!value) { alert("Invalid value"); location.href = "/errors/error.php"; }}var config = { urls: { invalid: "/errors/invalid.php" }, strs: { invalidmsg: "Invalid value" }};function validate(value) { if (!value) { alert(config.strs.invalidmsg); location.href = config.urls.invalid; }}
  • Module Pattern  Designate a single namespace for your applicationvar App = (function () { use strict; var settings; return { (function (app) { init: function(initialSettings){ // Private methods: settings = initialSettings; function find(query) { }, // Perform search } function verifyQuery(query) { getVersion: function (){ // Verify query return settings.version; } } // Public methods: = { }; find: find, verifyQuery: verifyQuery}()); }; }(App));
  • ECMA5
  • Use use strict Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a "strict" operating context. This strict context prevents certain actions from being taken and throws more exceptions (generally providing the user with more information and a tapered-down coding experience). Strict mode helps out in a couple ways:  It catches some common coding bloopers, throwing exceptions.  It prevents, or throws errors, when relatively "unsafe" actions are taken (such as gaining access to the global object).  It disables features that are confusing or poorly thought out.function imStrict(){ "use strict"; myVar = “test” // thrown exception}
  • Use JSON object JSON is syntax for storing and exchanging text information JSON is smaller than XML, and faster and easier to parse.var response = JSON.parse(xhr.responseText);console.log(;
  • Other Good Practices
  • Is jQuery your friend?
  • Don’t Mix Js And Html One of the most important best practices is to always separate JS code from HTML and go unobtrusive<a href="#" onclick="doSomething()"> Some Action</a><a href="#" id="link">Some Action</a><script type="text/javascript">var link = document.getElementById(link);link.addEventListener(“click”, function(){ // do something}, false);
  • Scripts at the Bottom of Your Page or use “async”or “defer” If you have JS files whose only purpose is to add functionality — for example, after a button is clicked — go ahead and place those files at the bottom, just before the closing body tag. This is absolutely a best practice. Async: Specifies that the script is executed asynchronously (only for external scripts) Defer: Specifies that the script is executed when the page has finished parsing (only for external scripts)
  • Deploying
  • Utilize JS Lint “JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems.”
  • Unit Testing oduction-to-javascript-unit-testing/ for-a-better-javascript-unit-test-tool Qunit Jasmine Other???
  • Unify + Minify…bundeling Build
  • Finishing
  • Tiny Tips Use Developer Tool - Chrome  JavaScript Profiling  Do more with Chrome Developer Tools JavaScript Errors Notifier
  • Read…Read…Read… JavaScript-Misunderstood.pdf