SlideShare une entreprise Scribd logo
1  sur  22
Javascript
Best Practices
Who can save us from this
       trouble?
Write CODE for
other
        Best practices is ZEN of
                          coding
JavaScript !== JAVA
JavaScript === ECMAScript
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
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
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 false




USE Strict Comparison Operators
        ( === & !== )
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];

    many

AVOID using global
variables

USE „var‟
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 {}
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)
Current
break       for          throw
case        function     try
catch       if           typeof
continue    in           var
default     instanceof   void
delete      new          while
do          return       with
else        switch
finally     this



           For Future
abstract    final        protected
boolean     float        public
byte        goto         short
char        implements   static
class       import       super
const       int          synchronized
debugger    interface    throws
double      long         transient
enum        native       volatile
export      package
extends     private
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
DON‟T Change a
Variable‟s Type After
 Initial Declaration
        var value = ‚One Hundred";
        value = 100;




       Not all change is good
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
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]);
}




                                               Better
var 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]);
}
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
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.
Value               Type
  0                   Number
  NaN                 Number
  ‘’                  String
  false               Boolean
  null                Object
  undefined           Undefined




The Falsy Values of
    Javascript
USE ‘.’ & [] notations
              wisely
               var x = obj[‘x’];                                   var x = obj.x;
               var x = obj[x];


  [] notation provides
                                                            dot notation is faster
  flexibility but is expensive


1. If a property is visible externally or is mixed with external properties than use
   square brackets
2. If a property is internal only to the project then use dot
3. If you're using a lot of square brackets think about binding it to a function
Thank you & HAPPY
    Coding
      break;

Contenu connexe

Tendances

5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScriptTodd Anglin
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design PatternsAddy Osmani
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To ClosureRobert Nyman
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Aaron Gustafson
 
JavaScript Best Pratices
JavaScript Best PraticesJavaScript Best Pratices
JavaScript Best PraticesChengHui Weng
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testingVikas Thange
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design PatternsPham Huy Tung
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101ygv2000
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript ProgrammingSehwan Noh
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module PatternsNicholas Jansma
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptStoyan Stefanov
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJamshid Hashimi
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsRan Mizrahi
 

Tendances (20)

5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
 
Scalable JavaScript Design Patterns
Scalable JavaScript Design PatternsScalable JavaScript Design Patterns
Scalable JavaScript Design Patterns
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
JavaScript Best Pratices
JavaScript Best PraticesJavaScript Best Pratices
JavaScript Best Pratices
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Javascript Module Patterns
Javascript Module PatternsJavascript Module Patterns
Javascript Module Patterns
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 

Similaire à Javascript best practices

Similaire à Javascript best practices (20)

Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
 
JavaScript patterns
JavaScript patternsJavaScript patterns
JavaScript patterns
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkJavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
 
node.js Module Development
node.js Module Developmentnode.js Module Development
node.js Module Development
 
05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards05 JavaScript #burningkeyboards
05 JavaScript #burningkeyboards
 
Js hacks
Js hacksJs hacks
Js hacks
 
Php & my sql
Php & my sqlPhp & my sql
Php & my sql
 
Enterprise js pratices
Enterprise js praticesEnterprise js pratices
Enterprise js pratices
 
Test driven node.js
Test driven node.jsTest driven node.js
Test driven node.js
 
Java script for web developer
Java script for web developerJava script for web developer
Java script for web developer
 
Advanced realm in swift
Advanced realm in swiftAdvanced realm in swift
Advanced realm in swift
 
Wakanday JS201 Best Practices
Wakanday JS201 Best PracticesWakanday JS201 Best Practices
Wakanday JS201 Best Practices
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
Stuff you didn't know about action script
Stuff you didn't know about action scriptStuff you didn't know about action script
Stuff you didn't know about action script
 
Everyday's JS
Everyday's JSEveryday's JS
Everyday's JS
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
 

Javascript best practices

  • 2. Who can save us from this trouble?
  • 3.
  • 4. Write CODE for other Best practices is ZEN of coding
  • 6. 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
  • 7. 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
  • 8. 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 false USE Strict Comparison Operators ( === & !== )
  • 9. 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]; many AVOID using global variables USE „var‟
  • 10. 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 {}
  • 11. 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)
  • 12. Current break for throw case function try catch if typeof continue in var default instanceof void delete new while do return with else switch finally this For Future abstract final protected boolean float public byte goto short char implements static class import super const int synchronized debugger interface throws double long transient enum native volatile export package extends private
  • 13. 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
  • 14.
  • 15. DON‟T Change a Variable‟s Type After Initial Declaration var value = ‚One Hundred"; value = 100; Not all change is good
  • 16. 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
  • 17. 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]); } Better var 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]); }
  • 18. 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
  • 19. 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.
  • 20. Value Type 0 Number NaN Number ‘’ String false Boolean null Object undefined Undefined The Falsy Values of Javascript
  • 21. USE ‘.’ & [] notations wisely var x = obj[‘x’]; var x = obj.x; var x = obj[x]; [] notation provides dot notation is faster flexibility but is expensive 1. If a property is visible externally or is mixed with external properties than use square brackets 2. If a property is internal only to the project then use dot 3. If you're using a lot of square brackets think about binding it to a function
  • 22. Thank you & HAPPY Coding break;