Javascript best practices

672 views
617 views

Published on

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
672
On SlideShare
0
From Embeds
0
Number of Embeds
7
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Javascript best practices

  1. 1. JavascriptBest Practices
  2. 2. Who can save us from this trouble?
  3. 3. Write CODE forother Best practices is ZEN of coding
  4. 4. JavaScript !== JAVAJavaScript === ECMAScript
  5. 5. Naming Conventions Type Good Examples Variables registrationDate, calValue Constants MAX_SIZE Functions resizeWindow, modTags Classes CM.view.createDoc.CreateDocumentPanel Objects configProperty, mixin, campaignData Filenames CreateDocumentPanel.js
  6. 6. i Adding a double slash before the closing star- slash allows you to comment and uncomment the whole block by simply adding or removing a slash before the opening slash-star./* */ instead of // function(){ var me = this; /* function enable(x){ x.setDisabled(false);COMMEN }; // */ }; T with
  7. 7. 0 == ‘0’ true 0 === ‘0’ false 1 == ‘1’ true 1 === ‘1’ false false == ‘0’ true false === ‘0’ false‘ nnn’ == 0 true ‘ nnn’ === 0 false ‘ ‘ == 0 true ‘ ‘ === 0 falseUSE Strict Comparison Operators ( === & !== )
  8. 8. function(data){ ! var localVar = data; //Correct : defines a local variable If you declare a variable, without using "var", globalVar = data; // declares a global variable the variable always becomes GLOBAL. }; Forgetting to declare a variable is a very common mistake. It creates bugs that can be very difficult to find. USE single var dayArray = [‘Mon’, ‘Tue’, ‘Wed’]; var dayArray = [‘Mon’, ‘Tue’, ‘Wed’], var dayArrayLength = dayArray.length; dayArrayLength = dayArray.length, ‘var’ instead of var dayOne = dayArray[0]; dayOne = dayArray[0]; manyAVOID using globalvariablesUSE „var‟
  9. 9. if (true) if (true){ UNCLEAR console.log("inside the if statement."); console.log("outside the if statement."); console.log("inside the if statement."); } console.log("outside the if statement.");var localVar = new Object(); var localVar = new Object{ name : ‘manav’; url : ‘http://about.me/manavg’; SLOW };var localVar = new Array(); var localVar = [‘manav’,’gaurav’];USE Braces {}
  10. 10. Statements that are effect by automatic semicolon insertion empty var expression return do-while ’something’; continue // is transformed to break return; return ’something’; throw Automatic ; (semicolon)
  11. 11. Currentbreak for throwcase function trycatch if typeofcontinue in vardefault instanceof voiddelete new whiledo return withelse switchfinally this For Futureabstract final protectedboolean float publicbyte goto shortchar implements staticclass import superconst int synchronizeddebugger interface throwsdouble long transientenum native volatileexport packageextends private
  12. 12. switch (color) { case ‘blue’:if (color === ‘blue’) { // do something here... // do something here... break;} else if (color === ‘green’) { case ‘green’: // do something here... // do something here...} else if (color === ‘yellow’) { break; // do something here... case ‘yellow’:} else if (color === ‘red’) { // do something here... // do something here... break;} else { case ‘red’: // do something here... // do something here...} break; default: // do something here... USE the “switch” to } Handle Multiple Conditions
  13. 13. DON‟T Change aVariable‟s Type After Initial Declaration var value = ‚One Hundred"; value = 100; Not all change is good
  14. 14. var human = {var human = new Object(); name : ‘Manav’,human.name = ‘Manav’; gender : ‘male’,human.gender = ‘male’; say : function(){human.say = function(){ return ‘I am’ + this.name; return ‘I am’ + this.name; }}; }; var department = [var department = new Array(); ‘Engineering’,department[0] = ‘Engineering’; ‘Operations’,department[1] = ‘Operations’; ‘Management’department[2] = ‘Management’; ];var direction;if(x > 0){ direction = ‘right’; var direction = (x > 0) ? ‘right’ : ‘left’;} else { direction = ‘left’;}if(v){ var x = v;} else { var x = v ? v : 10; var x = v || 10;} var x = 10; USE Shortcut
  15. 15. Optimize loops What could be faster?var names = [Red,Blue,Green,‘Yellow];for(var i=0;i<names.length;i++){ meshColor (names[i], names[i-1]);} Bettervar names = [Red,Blue,Green,‘Yellow];var all = names.length;for(var i=0;i<all;i++){ meshColor(names[i], names[i-1]);}var names = [Red,Blue,Green,‘Yellow];for(var i=0,j=names.length;i<j;i++){ meshColor (names[i], names[i-1]);}
  16. 16. function showUsers(users) { /* verify that users is an non-empty array */ if(typeof users === ‚array‛ && users.length) { /* process users array */ }function callback(data) { } /* verify that data is not null */ if(!data) { throw new Error(‚CampaignService.getCampaignData returned null.‛); return false; } /* process data */} function saveForm() { var f = this.getForm(); if(!f.isValid()) { alert(‚Fill in the form as required.‛); return false; } /* save data */ } DON‟T Trust External Data
  17. 17. USE Object Literals as Configuration Objects Ext.create({Object literals are objects xtype: ‚textfield‛, name: ‛firstName‛,defined using braces {} that label: ‚First Name‛,contain a set of comma allowBlank: false, readOnly: false,separated key-value pairs much minLength: 10 });like a map in Java.
  18. 18. Value Type 0 Number NaN Number ‘’ String false Boolean null Object undefined UndefinedThe Falsy Values of Javascript
  19. 19. USE ‘.’ & [] notations wisely var x = obj[‘x’]; var x = obj.x; var x = obj[x]; [] notation provides dot notation is faster flexibility but is expensive1. If a property is visible externally or is mixed with external properties than use square brackets2. If a property is internal only to the project then use dot3. If youre using a lot of square brackets think about binding it to a function
  20. 20. Thank you & HAPPY Coding break;

×