Java script best practices


Published on

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

  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • Java script best practices

    1. 1. “JavaScript: It is the language thatpeople use without bothering tolearn it first” Douglas Crockford
    2. 2. Coding
    3. 3. 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
    4. 4. 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]();
    5. 5. 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(;
    6. 6. 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”
    7. 7. 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();​
    8. 8. 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]);}
    9. 9. 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. ");}
    10. 10. String Concatenation (cont.)
    11. 11. 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];
    12. 12. "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... }}
    13. 13. 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);
    14. 14. 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); <--- ???
    15. 15. 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}
    16. 16. 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
    17. 17. Debuggingconsole.log( firstVariable, secondVariable, xVariable);console.clear();
    18. 18. 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() { ...}
    19. 19. 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]);}
    20. 20. Patterns
    21. 21. 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);
    22. 22. 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 };})();
    23. 23. 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);}
    24. 24. 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; }}
    25. 25. 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));
    26. 26. ECMA5
    27. 27. 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}
    28. 28. 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(;
    29. 29. Other Good Practices
    30. 30. Is jQuery your friend?
    31. 31. 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);
    32. 32. 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)
    33. 33. Deploying
    34. 34. 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.”
    35. 35. Unit Testing oduction-to-javascript-unit-testing/ for-a-better-javascript-unit-test-tool Qunit Jasmine Other???
    36. 36. Unify + Minify…bundeling Build
    37. 37. Finishing
    38. 38. Tiny Tips Use Developer Tool - Chrome  JavaScript Profiling  Do more with Chrome Developer Tools JavaScript Errors Notifier
    39. 39. Read…Read…Read… JavaScript-Misunderstood.pdf