Java script best practices

40
JavaScript Best Practices

description

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

Transcript of Java script best practices

  • 1. JavaScript: It is the language thatpeople use without bothering tolearn it first Douglas Crockford

2. Coding 3. Use === instead of == However, when working with == and !=, youll run intoissues when working with different types. In thesecases, theyll 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. Eval is Bad Not only will this decrease your scripts performancesubstantially, but it also poses a huge security riskbecause it grants far too much power to the passed intext. 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. Dont 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(DudeNameSpace.name); 6. Always declare your variables using var If you declare a variable, without using "var", thevariable always becomes GLOBAL.function test(){ name = "Jean"; //this is global}test();console.log(name) // Jean 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. Declare Variables Outside of the ForStatement When executing lengthy for statements, dont 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 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. String Concatenation (cont.) http://jsperf.com/javascript-string-concatenation 11. Use [] Instead of New Array() "A common error in JavaScript programs is to use an object whenan array is required or an array when an object is required. Therule is simple: when the property names are small sequentialintegers, 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. "For in" Statements When looping through items in an object, you might findthat youll also retrieve method functions as well. In orderto work around this, always wrap your code in an ifstatement which filters the information Dont use for in to loop a array slow performancefor(key in object) { if(object.hasOwnProperty(key) {...then do something... }} 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. Starting Curly Brace On The Same Line Thats one of the pitfalls of javascript: automaticsemicolon insertionfunction myFunc(){return;{name: sarfraz};}var f = myFunc();console.log(f);