Maintainable JavaScript

Nicholas Zakas
Nicholas ZakasFront End Guy at Box
Maintainable JavaS cript

        Nicholas C . Zakas
   S r. Frontend E ngineer, M y
              Yahoo!
Why?
                     Writing New
                        Code




Maintaining
   Code
Who cares ?
• Your employer
• Your co-workers, present and future
• D evelopment community
What is maintainability?
•   Understandable
•   Intuitive
•   Adaptable
•   E xtendable
•   D ebuggable
C ode C onventions
     M aintainable JavaS cript
R eadable code
• Indent your code
• C omment your code
  –   E ach method
  –   Large sections of code
  –   D ifficult-to-understand algorithms
  –   Hacks
Naming
• Use logical names for variables and
  functions
  – D on’t worry about length
• Variable names should be nouns (i.e., car)
• Function names should begin with a verb
  (i.e., getName())
  – For functions returning Boolean values, prefix
    with “is”, such as isValid()
• Avoid useless names such as foo, bar,
  temp
Indicate variable type
• Initialization
  var found = false;


• Hungarian Notation
  var sName = quot;Nicholasquot;;


• Type C omments
  var cost /*:float*/ = 5.23;
Loos e C oupling
     M aintainable JavaS cript
C lient-s ide Layers

  Behavior       Presentation
(JavaScript)        (CSS)

          Structure
          (HTML)
S eparate HTML and
           JavaS cript
• JavaS cript in HTM L
 <a onclick=quot;sayHi()quot;>text</a>


• HTM L in JavaS cript
  element.innerHTML = quot;<div>quot;
 + quot;<a href=quot;/js/quot;>text</a></div>quot;;
S eparate C S S and
             JavaS cript
• JavaS cript in C S S
  div.hd {
    width:
        expression(ref.offsetWidth+quot;pxquot;);
  }


• C S S in JavaS cript
  element.style.color = quot;redquot;;
E vent handlers handle
           events
function handleKeyPress(event){
  if (event.keyCode == 13){
     var value = 5 *
               parseInt(txt.value);
     div.innerHTML = value;
     alert(quot;Updatedquot;);
  }
}
E vent handlers handle
           events
function handleKeyPress(event){
  if (event.keyCode == 13){
     performCalculation();
     updateUI();
  }
}
Prog ramming Practices
    M aintainable JavaS cript
Don’t Modify Objects You
         Don’t Own
• D on’t add methods
• D on’t override methods

• You don’t own O bject, Array, R egE xp,
  S tring, Number, B oolean, D ate,
  Function
Avoid g lobals
• All publicly-accessible
  functions/ variables should be attached
  to an object
• Namespace your objects
  – D on’t go overboard
  – Three levels is enough

YAHOO.Way.Too.Long.Namespace
Don’t overus e popular
          techniques
• C losures/nested functions
  – Use sparingly
• O bject literals
  – S ingletons
  – P ass data
Throw your own errors
function add5(value) {
  if (arguments.length < 1) {
   throw new
      Error(quot;add5: Not enough argsquot;);
  }

    return value + 5;
}
Avoid null comparis ons
function sortArray(value) {
  if (value != null) {
     value.sort();
  }
}
Avoid null comparis ons
function sortArray(value) {
  if (value instanceof Array) {
     value.sort();
  }
}
Avoid null comparis ons
function sortArray(value) {
  if (value instanceof Array) {
     value.sort();
  } else {
     throw new Error(quot;sortArray:
  argument must be an array.quot;);
  }
}
Avoid null comparis ons
• Use instanceof for specific types of
  objects
 if (value instanceof
 constructor){


• Use typeof to test for string, number,
  B oolean
 if (typeof value == quot;stringquot;) {
Us e C ons tants
function validate(value) {
  if (!value) {
    alert(quot;Invalid valuequot;);
    location.href =
            quot;/errors/invalid.phpquot;;
  }
}
Us e C ons tants
var Constants = {
   INVALID_MSG : quot;Invalid valuequot;,
   INVALID_URL : quot;/errors/invalid.phpquot;
};
function validate(value) {
   if (!value) {
     alert(Constants.INVALID_MSG);
     location.href =
             Constants.INVALID_URL;
   }
}
Us e C ons tants
•   R epeated unique values
•   UI strings
•   UR Ls
•   Any value that may change in the future
B uild Proces s
     M aintainable JavaS cript
B uild Proces s


    Source Files


       Build
R ecommendations
• O ne object or object definition per file
  – Indicate dependencies
• Use a build step
  – C ombine files in appropriate order
  – S trip comments/ whitespace
  – Validate code
S ummary
    M aintainable JavaS cript
S ummary
•   C ode C onventions
•   Loose C oupling
•   P rogramming P ractices
•   B uild P rocess
Ques tions and Ans wers
     M aintainable JavaS cript
E tcetera
• M y email:   nzakas@ yahoo-inc.com
• M y blog:    www.nczonline.net
1 of 33

Recommended

Test Driven Development With YUI Test (Ajax Experience 2008) by
Test Driven Development With YUI Test (Ajax Experience 2008)Test Driven Development With YUI Test (Ajax Experience 2008)
Test Driven Development With YUI Test (Ajax Experience 2008)Nicholas Zakas
31.1K views73 slides
JavaScript - From Birth To Closure by
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To ClosureRobert Nyman
51.9K views133 slides
Maintainable JavaScript 2011 by
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011Nicholas Zakas
12.1K views53 slides
JavaScript APIs you’ve never heard of (and some you have) by
JavaScript APIs you’ve never heard of (and some you have)JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)Nicholas Zakas
51.4K views67 slides
Gtg12 by
Gtg12Gtg12
Gtg12Poga Po
1.6K views37 slides
RSpec by
RSpecRSpec
RSpecMarco Otte-Witte
1K views32 slides

More Related Content

What's hot

Javascript by
JavascriptJavascript
JavascriptAditya Gaur
1.1K views25 slides
Advanced Javascript by
Advanced JavascriptAdvanced Javascript
Advanced JavascriptDhruvin Shah
145 views16 slides
JavaScript Library Overview by
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overviewjeresig
30.7K views83 slides
Introduction to Javascript by
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
13.5K views46 slides
Easy automation.py by
Easy automation.pyEasy automation.py
Easy automation.pyIakiv Kramarenko
507 views82 slides
Javascript by
JavascriptJavascript
Javascripttheacadian
1.4K views101 slides

What's hot(20)

JavaScript Library Overview by jeresig
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overview
jeresig30.7K views
Introduction to Javascript by Amit Tyagi
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi13.5K views
Javascript by theacadian
JavascriptJavascript
Javascript
theacadian1.4K views
Javascript basics for automation testing by Vikas Thange
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
Vikas Thange666 views
Nikita Popov "What’s new in PHP 8.0?" by Fwdays
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
Fwdays526 views
JavaScript Best Pratices by ChengHui Weng
JavaScript Best PraticesJavaScript Best Pratices
JavaScript Best Pratices
ChengHui Weng359 views
5 Tips for Better JavaScript by Todd Anglin
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
Todd Anglin72.5K views
JavaScript - Chapter 5 - Operators by WebStackAcademy
 JavaScript - Chapter 5 - Operators JavaScript - Chapter 5 - Operators
JavaScript - Chapter 5 - Operators
WebStackAcademy1.1K views
Exception Handling: Designing Robust Software in Ruby by Wen-Tien Chang
Exception Handling: Designing Robust Software in RubyException Handling: Designing Robust Software in Ruby
Exception Handling: Designing Robust Software in Ruby
Wen-Tien Chang11.9K views
8 introduction to_java_script by Vijay Kalyan
8 introduction to_java_script8 introduction to_java_script
8 introduction to_java_script
Vijay Kalyan1.3K views
LinkedIn TBC JavaScript 100: Intro by Adam Crabtree
LinkedIn TBC JavaScript 100: IntroLinkedIn TBC JavaScript 100: Intro
LinkedIn TBC JavaScript 100: Intro
Adam Crabtree518 views

Similar to Maintainable JavaScript

JavaScript - Chapter 4 - Types and Statements by
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and StatementsWebStackAcademy
1.5K views67 slides
javascript teach by
javascript teachjavascript teach
javascript teachguest3732fa
1.2K views155 slides
JSBootcamp_White by
JSBootcamp_WhiteJSBootcamp_White
JSBootcamp_Whiteguest3732fa
907 views155 slides
Java script final presentation by
Java script final presentationJava script final presentation
Java script final presentationAdhoura Academy
3.8K views51 slides
Javascript by
JavascriptJavascript
Javascriptvikram singh
970 views142 slides
Java Intro by
Java IntroJava Intro
Java Introbackdoor
4.4K views30 slides

Similar to Maintainable JavaScript(20)

JavaScript - Chapter 4 - Types and Statements by WebStackAcademy
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
WebStackAcademy1.5K views
javascript teach by guest3732fa
javascript teachjavascript teach
javascript teach
guest3732fa1.2K views
JSBootcamp_White by guest3732fa
JSBootcamp_WhiteJSBootcamp_White
JSBootcamp_White
guest3732fa907 views
Java script final presentation by Adhoura Academy
Java script final presentationJava script final presentation
Java script final presentation
Adhoura Academy3.8K views
Java Intro by backdoor
Java IntroJava Intro
Java Intro
backdoor4.4K views
Basics of Javascript by Universe41
Basics of JavascriptBasics of Javascript
Basics of Javascript
Universe414 views
Automated Frontend Testing by Neil Crosby
Automated Frontend TestingAutomated Frontend Testing
Automated Frontend Testing
Neil Crosby11.6K views
Php Inspections (EA Extended): if-conditions optimization by Vladimir Reznichenko
Php Inspections (EA Extended): if-conditions optimizationPhp Inspections (EA Extended): if-conditions optimization
Php Inspections (EA Extended): if-conditions optimization
Efficient JavaScript Development by wolframkriesing
Efficient JavaScript DevelopmentEfficient JavaScript Development
Efficient JavaScript Development
wolframkriesing962 views
Jumping Into Java Then! by mondodello
Jumping Into Java Then!Jumping Into Java Then!
Jumping Into Java Then!
mondodello259 views
Scala + WattzOn, sitting in a tree.... by Raffi Krikorian
Scala + WattzOn, sitting in a tree....Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....
Raffi Krikorian1.6K views
SproutCore and the Future of Web Apps by Mike Subelsky
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
Mike Subelsky708 views
An Introduction To jQuery by Andy Gibson
An Introduction To jQueryAn Introduction To jQuery
An Introduction To jQuery
Andy Gibson517 views
Jscript Fundamentals by rspaike
Jscript FundamentalsJscript Fundamentals
Jscript Fundamentals
rspaike621 views
Functional Java 8 - Introduction by Łukasz Biały
Functional Java 8 - IntroductionFunctional Java 8 - Introduction
Functional Java 8 - Introduction
Łukasz Biały637 views
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge by Guillaume Laforge
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume LaforgeGroovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge
Groovy in the Enterprise - Case Studies - TSSJS Prague 2008 - Guillaume Laforge
Guillaume Laforge1.1K views

More from Nicholas Zakas

Browser Wars Episode 1: The Phantom Menace by
Browser Wars Episode 1: The Phantom MenaceBrowser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom MenaceNicholas Zakas
77.4K views168 slides
Enough with the JavaScript already! by
Enough with the JavaScript already!Enough with the JavaScript already!
Enough with the JavaScript already!Nicholas Zakas
260K views84 slides
The Pointerless Web by
The Pointerless WebThe Pointerless Web
The Pointerless WebNicholas Zakas
7K views64 slides
JavaScript Timers, Power Consumption, and Performance by
JavaScript Timers, Power Consumption, and PerformanceJavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and PerformanceNicholas Zakas
54.4K views128 slides
Scalable JavaScript Application Architecture 2012 by
Scalable JavaScript Application Architecture 2012Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012Nicholas Zakas
94K views114 slides
Maintainable JavaScript 2012 by
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012Nicholas Zakas
90.8K views85 slides

More from Nicholas Zakas(20)

Browser Wars Episode 1: The Phantom Menace by Nicholas Zakas
Browser Wars Episode 1: The Phantom MenaceBrowser Wars Episode 1: The Phantom Menace
Browser Wars Episode 1: The Phantom Menace
Nicholas Zakas77.4K views
Enough with the JavaScript already! by Nicholas Zakas
Enough with the JavaScript already!Enough with the JavaScript already!
Enough with the JavaScript already!
Nicholas Zakas260K views
JavaScript Timers, Power Consumption, and Performance by Nicholas Zakas
JavaScript Timers, Power Consumption, and PerformanceJavaScript Timers, Power Consumption, and Performance
JavaScript Timers, Power Consumption, and Performance
Nicholas Zakas54.4K views
Scalable JavaScript Application Architecture 2012 by Nicholas Zakas
Scalable JavaScript Application Architecture 2012Scalable JavaScript Application Architecture 2012
Scalable JavaScript Application Architecture 2012
Nicholas Zakas94K views
Maintainable JavaScript 2012 by Nicholas Zakas
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012
Nicholas Zakas90.8K views
High Performance JavaScript (CapitolJS 2011) by Nicholas Zakas
High Performance JavaScript (CapitolJS 2011)High Performance JavaScript (CapitolJS 2011)
High Performance JavaScript (CapitolJS 2011)
Nicholas Zakas57.5K views
High Performance JavaScript 2011 by Nicholas Zakas
High Performance JavaScript 2011High Performance JavaScript 2011
High Performance JavaScript 2011
Nicholas Zakas10.1K views
Mobile Web Speed Bumps by Nicholas Zakas
Mobile Web Speed BumpsMobile Web Speed Bumps
Mobile Web Speed Bumps
Nicholas Zakas13.4K views
High Performance JavaScript (Amazon DevCon 2011) by Nicholas Zakas
High Performance JavaScript (Amazon DevCon 2011)High Performance JavaScript (Amazon DevCon 2011)
High Performance JavaScript (Amazon DevCon 2011)
Nicholas Zakas4.6K views
Progressive Enhancement 2.0 (Conference Agnostic) by Nicholas Zakas
Progressive Enhancement 2.0 (Conference Agnostic)Progressive Enhancement 2.0 (Conference Agnostic)
Progressive Enhancement 2.0 (Conference Agnostic)
Nicholas Zakas42.5K views
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011) by Nicholas Zakas
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Progressive Enhancement 2.0 (jQuery Conference SF Bay Area 2011)
Nicholas Zakas10.1K views
YUI Test The Next Generation (YUIConf 2010) by Nicholas Zakas
YUI Test The Next Generation (YUIConf 2010)YUI Test The Next Generation (YUIConf 2010)
YUI Test The Next Generation (YUIConf 2010)
Nicholas Zakas3.7K views
High Performance JavaScript (YUIConf 2010) by Nicholas Zakas
High Performance JavaScript (YUIConf 2010)High Performance JavaScript (YUIConf 2010)
High Performance JavaScript (YUIConf 2010)
Nicholas Zakas61.8K views
High Performance JavaScript - Fronteers 2010 by Nicholas Zakas
High Performance JavaScript - Fronteers 2010High Performance JavaScript - Fronteers 2010
High Performance JavaScript - Fronteers 2010
Nicholas Zakas4.2K views
Nicholas' Performance Talk at Google by Nicholas Zakas
Nicholas' Performance Talk at GoogleNicholas' Performance Talk at Google
Nicholas' Performance Talk at Google
Nicholas Zakas4.6K views
High Performance JavaScript - WebDirections USA 2010 by Nicholas Zakas
High Performance JavaScript - WebDirections USA 2010High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010
Nicholas Zakas59.7K views
Performance on the Yahoo! Homepage by Nicholas Zakas
Performance on the Yahoo! HomepagePerformance on the Yahoo! Homepage
Performance on the Yahoo! Homepage
Nicholas Zakas7.9K views
High Performance JavaScript - jQuery Conference SF Bay Area 2010 by Nicholas Zakas
High Performance JavaScript - jQuery Conference SF Bay Area 2010High Performance JavaScript - jQuery Conference SF Bay Area 2010
High Performance JavaScript - jQuery Conference SF Bay Area 2010
Nicholas Zakas47.7K views

Recently uploaded

SAP Automation Using Bar Code and FIORI.pdf by
SAP Automation Using Bar Code and FIORI.pdfSAP Automation Using Bar Code and FIORI.pdf
SAP Automation Using Bar Code and FIORI.pdfVirendra Rai, PMP
25 views38 slides
Democratising digital commerce in India-Report by
Democratising digital commerce in India-ReportDemocratising digital commerce in India-Report
Democratising digital commerce in India-ReportKapil Khandelwal (KK)
20 views161 slides
Business Analyst Series 2023 - Week 3 Session 5 by
Business Analyst Series 2023 -  Week 3 Session 5Business Analyst Series 2023 -  Week 3 Session 5
Business Analyst Series 2023 - Week 3 Session 5DianaGray10
345 views20 slides
Ransomware is Knocking your Door_Final.pdf by
Ransomware is Knocking your Door_Final.pdfRansomware is Knocking your Door_Final.pdf
Ransomware is Knocking your Door_Final.pdfSecurity Bootcamp
66 views46 slides
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院 by
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院IttrainingIttraining
69 views8 slides
PRODUCT PRESENTATION.pptx by
PRODUCT PRESENTATION.pptxPRODUCT PRESENTATION.pptx
PRODUCT PRESENTATION.pptxangelicacueva6
18 views1 slide

Recently uploaded(20)

SAP Automation Using Bar Code and FIORI.pdf by Virendra Rai, PMP
SAP Automation Using Bar Code and FIORI.pdfSAP Automation Using Bar Code and FIORI.pdf
SAP Automation Using Bar Code and FIORI.pdf
Business Analyst Series 2023 - Week 3 Session 5 by DianaGray10
Business Analyst Series 2023 -  Week 3 Session 5Business Analyst Series 2023 -  Week 3 Session 5
Business Analyst Series 2023 - Week 3 Session 5
DianaGray10345 views
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院 by IttrainingIttraining
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
【USB韌體設計課程】精選講義節錄-USB的列舉過程_艾鍗學院
Piloting & Scaling Successfully With Microsoft Viva by Richard Harbridge
Piloting & Scaling Successfully With Microsoft VivaPiloting & Scaling Successfully With Microsoft Viva
Piloting & Scaling Successfully With Microsoft Viva
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors by sugiuralab
TouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective SensorsTouchLog: Finger Micro Gesture Recognition  Using Photo-Reflective Sensors
TouchLog: Finger Micro Gesture Recognition Using Photo-Reflective Sensors
sugiuralab23 views
PharoJS - Zürich Smalltalk Group Meetup November 2023 by Noury Bouraqadi
PharoJS - Zürich Smalltalk Group Meetup November 2023PharoJS - Zürich Smalltalk Group Meetup November 2023
PharoJS - Zürich Smalltalk Group Meetup November 2023
Noury Bouraqadi139 views
The Forbidden VPN Secrets.pdf by Mariam Shaba
The Forbidden VPN Secrets.pdfThe Forbidden VPN Secrets.pdf
The Forbidden VPN Secrets.pdf
Mariam Shaba20 views
"Surviving highload with Node.js", Andrii Shumada by Fwdays
"Surviving highload with Node.js", Andrii Shumada "Surviving highload with Node.js", Andrii Shumada
"Surviving highload with Node.js", Andrii Shumada
Fwdays33 views
HTTP headers that make your website go faster - devs.gent November 2023 by Thijs Feryn
HTTP headers that make your website go faster - devs.gent November 2023HTTP headers that make your website go faster - devs.gent November 2023
HTTP headers that make your website go faster - devs.gent November 2023
Thijs Feryn26 views
STPI OctaNE CoE Brochure.pdf by madhurjyapb
STPI OctaNE CoE Brochure.pdfSTPI OctaNE CoE Brochure.pdf
STPI OctaNE CoE Brochure.pdf
madhurjyapb14 views

Maintainable JavaScript

  • 1. Maintainable JavaS cript Nicholas C . Zakas S r. Frontend E ngineer, M y Yahoo!
  • 2. Why? Writing New Code Maintaining Code
  • 3. Who cares ? • Your employer • Your co-workers, present and future • D evelopment community
  • 4. What is maintainability? • Understandable • Intuitive • Adaptable • E xtendable • D ebuggable
  • 5. C ode C onventions M aintainable JavaS cript
  • 6. R eadable code • Indent your code • C omment your code – E ach method – Large sections of code – D ifficult-to-understand algorithms – Hacks
  • 7. Naming • Use logical names for variables and functions – D on’t worry about length • Variable names should be nouns (i.e., car) • Function names should begin with a verb (i.e., getName()) – For functions returning Boolean values, prefix with “is”, such as isValid() • Avoid useless names such as foo, bar, temp
  • 8. Indicate variable type • Initialization var found = false; • Hungarian Notation var sName = quot;Nicholasquot;; • Type C omments var cost /*:float*/ = 5.23;
  • 9. Loos e C oupling M aintainable JavaS cript
  • 10. C lient-s ide Layers Behavior Presentation (JavaScript) (CSS) Structure (HTML)
  • 11. S eparate HTML and JavaS cript • JavaS cript in HTM L <a onclick=quot;sayHi()quot;>text</a> • HTM L in JavaS cript element.innerHTML = quot;<div>quot; + quot;<a href=quot;/js/quot;>text</a></div>quot;;
  • 12. S eparate C S S and JavaS cript • JavaS cript in C S S div.hd { width: expression(ref.offsetWidth+quot;pxquot;); } • C S S in JavaS cript element.style.color = quot;redquot;;
  • 13. E vent handlers handle events function handleKeyPress(event){ if (event.keyCode == 13){ var value = 5 * parseInt(txt.value); div.innerHTML = value; alert(quot;Updatedquot;); } }
  • 14. E vent handlers handle events function handleKeyPress(event){ if (event.keyCode == 13){ performCalculation(); updateUI(); } }
  • 15. Prog ramming Practices M aintainable JavaS cript
  • 16. Don’t Modify Objects You Don’t Own • D on’t add methods • D on’t override methods • You don’t own O bject, Array, R egE xp, S tring, Number, B oolean, D ate, Function
  • 17. Avoid g lobals • All publicly-accessible functions/ variables should be attached to an object • Namespace your objects – D on’t go overboard – Three levels is enough YAHOO.Way.Too.Long.Namespace
  • 18. Don’t overus e popular techniques • C losures/nested functions – Use sparingly • O bject literals – S ingletons – P ass data
  • 19. Throw your own errors function add5(value) { if (arguments.length < 1) { throw new Error(quot;add5: Not enough argsquot;); } return value + 5; }
  • 20. Avoid null comparis ons function sortArray(value) { if (value != null) { value.sort(); } }
  • 21. Avoid null comparis ons function sortArray(value) { if (value instanceof Array) { value.sort(); } }
  • 22. Avoid null comparis ons function sortArray(value) { if (value instanceof Array) { value.sort(); } else { throw new Error(quot;sortArray: argument must be an array.quot;); } }
  • 23. Avoid null comparis ons • Use instanceof for specific types of objects if (value instanceof constructor){ • Use typeof to test for string, number, B oolean if (typeof value == quot;stringquot;) {
  • 24. Us e C ons tants function validate(value) { if (!value) { alert(quot;Invalid valuequot;); location.href = quot;/errors/invalid.phpquot;; } }
  • 25. Us e C ons tants var Constants = { INVALID_MSG : quot;Invalid valuequot;, INVALID_URL : quot;/errors/invalid.phpquot; }; function validate(value) { if (!value) { alert(Constants.INVALID_MSG); location.href = Constants.INVALID_URL; } }
  • 26. Us e C ons tants • R epeated unique values • UI strings • UR Ls • Any value that may change in the future
  • 27. B uild Proces s M aintainable JavaS cript
  • 28. B uild Proces s Source Files Build
  • 29. R ecommendations • O ne object or object definition per file – Indicate dependencies • Use a build step – C ombine files in appropriate order – S trip comments/ whitespace – Validate code
  • 30. S ummary M aintainable JavaS cript
  • 31. S ummary • C ode C onventions • Loose C oupling • P rogramming P ractices • B uild P rocess
  • 32. Ques tions and Ans wers M aintainable JavaS cript
  • 33. E tcetera • M y email: nzakas@ yahoo-inc.com • M y blog: www.nczonline.net