SlideShare a Scribd company logo
Javascript
Best Practices
Who can save us from this
       trouble?
Javascript best practices
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
Javascript best practices
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;

More Related Content

PDF
Secrets of JavaScript Libraries
PDF
Patterns for JVM languages - Geecon 2014
ZIP
Fundamental JavaScript [In Control 2009]
PPT
Javascript and Jquery Best practices
PDF
Performance Optimization and JavaScript Best Practices
PDF
Javascript Best Practices
PDF
JavaScript Basics and Best Practices - CC FE & UX
PDF
Ten useful JavaScript tips & best practices
Secrets of JavaScript Libraries
Patterns for JVM languages - Geecon 2014
Fundamental JavaScript [In Control 2009]
Javascript and Jquery Best practices
Performance Optimization and JavaScript Best Practices
Javascript Best Practices
JavaScript Basics and Best Practices - CC FE & UX
Ten useful JavaScript tips & best practices

What's hot (20)

PPTX
5 Tips for Better JavaScript
PDF
Scalable JavaScript Design Patterns
PDF
JavaScript - From Birth To Closure
PDF
Fundamental JavaScript [UTC, March 2014]
PDF
JavaScript Best Pratices
PDF
Javascript Design Patterns
PDF
Java Script Best Practices
PPTX
Javascript basics for automation testing
PPTX
Javascript Common Design Patterns
PDF
JavaScript 101
ODP
Javascript
PDF
JavaScript Programming
PDF
Javascript Module Patterns
PDF
Javascript basics
PPT
Beginning Object-Oriented JavaScript
PDF
Intro to JavaScript
PPTX
Intro to Javascript
PPTX
JavaScript Fundamentals & JQuery
PDF
How AngularJS Embraced Traditional Design Patterns
PPT
JavaScript Basics
5 Tips for Better JavaScript
Scalable JavaScript Design Patterns
JavaScript - From Birth To Closure
Fundamental JavaScript [UTC, March 2014]
JavaScript Best Pratices
Javascript Design Patterns
Java Script Best Practices
Javascript basics for automation testing
Javascript Common Design Patterns
JavaScript 101
Javascript
JavaScript Programming
Javascript Module Patterns
Javascript basics
Beginning Object-Oriented JavaScript
Intro to JavaScript
Intro to Javascript
JavaScript Fundamentals & JQuery
How AngularJS Embraced Traditional Design Patterns
JavaScript Basics
Ad

Similar to Javascript best practices (20)

PDF
Javascript: the important bits
PDF
Say It With Javascript
PDF
ES6 - Next Generation Javascript
PDF
JavaScript patterns
ODP
ES6 PPT FOR 2016
KEY
JavaScript Neednt Hurt - JavaBin talk
PDF
node.js Module Development
PDF
05 JavaScript #burningkeyboards
PDF
PPTX
Php & my sql
PPTX
Enterprise js pratices
PDF
Test driven node.js
PPTX
Java script for web developer
PDF
Advanced realm in swift
PPT
Wakanday JS201 Best Practices
PDF
CoffeeScript
PDF
Stuff you didn't know about action script
PPTX
Everyday's JS
PPTX
ES6 Overview
PDF
Javascript & Ajax Basics
Javascript: the important bits
Say It With Javascript
ES6 - Next Generation Javascript
JavaScript patterns
ES6 PPT FOR 2016
JavaScript Neednt Hurt - JavaBin talk
node.js Module Development
05 JavaScript #burningkeyboards
Php & my sql
Enterprise js pratices
Test driven node.js
Java script for web developer
Advanced realm in swift
Wakanday JS201 Best Practices
CoffeeScript
Stuff you didn't know about action script
Everyday's JS
ES6 Overview
Javascript & Ajax Basics
Ad

Javascript best practices

  • 2. Who can save us from this trouble?
  • 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
  • 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;