Clean Javascript

by Nathan Birrell

1. Clean Code

Maintainable, Readable, Simple, Tested

Total cost of owning a mess

2. Meaningful Names

2. Meaningful Names

3. Functions

3. Functions

// bad
self.init = function() {
 // WS call in init :(
 $.get(API_URL_MANAGE_SERVICE).done(function(result) {
  // too many lines of logic inside .done() :(
  var oldService;
  
  self.allServices(result.manageService.availablePlans.terms);
  
  self.initSelectedServiceAndVisibleServices();
  
  oldService = result.manageService;
  
  if (result.updateState) {
   // 3 levels deep in indentation, difficult to read
   self.updateState(result.updateState);
   delete oldService.updateState;
  }
  
  delete oldService.availablePlans; 
  self.oldService(oldService);
  
  self.initialiseCardsStatus();
 });
 
 // Mixing layers of abstraction -- this is an INIT function (high level)
 // Unnecessary comments
 var summaryTitleHeight = 70; // height of title is always 70
 var summaryContainerOffset = $('#ctn-service-summary').offset().top;
 var summaryInView =
  (summaryContainerOffset + summaryTitleHeight) - $(window).height() - $(window).scrollTop() < 0;
  
 self.serviceSummarySection.stickySummary(!summaryInView);
};

3. Functions

// good 
self.init = function() {
 self.apiRetrieve();
 self.initialiseCardsStatus();
 self.serviceSummarySection.setStickySummary();
};

self.apiRetrieve = function() {
 $.get(API_URL_MANAGE_SERVICE)
 .done(function(result) {
  try {
   self.parseApiData(result);
  } catch (e) {
   self.viewState.serverError(true);
  }
 });
 // handle fail, etc. etc.
};

4. Comments

Finally

Thanks :)@nathanbirrell