SlideShare a Scribd company logo
JavaScript
       “Best Practices”


Christian Heilmann | http://wait-till-i.com | http://scriptingenabled.org

       Bangalore, India, Yahoo internal training, February 2009
“Best Practice” presentations
       are hard to do.
Trying to tell developers to
change their ways and follow
your example is a tough call.
I also consider it a flawed
         process.
I am bored of discussions of
      syntax details.
This is not about
 forcing you to
 believe what I
    believe.
This is about telling you what
 worked for me and might as
       well work for you.
I’ve collected a lot of ideas
and tips over time how to be
       more effective.
Avoid heavy nesting
Make it understandable
                                 Optimize loops
Avoid globals
                                 Keep DOM access to a
Stick to a strict coding style
                                 minimum
Comment as much as needed
                                 Don't yield to browser whims
but not more
                                 Don't trust any data
Avoid mixing with other
technologies
                                 Add functionality with
                                 JavaScript, not content
Use shortcut notations
                                 Build on the shoulders of
Modularize
                                 giants
Enhance progressively
                                 Development code is not live
Allow for configuration and      code
translation
Make it understandable!
Choose easy to understand
and short names for variables
       and functions.
Bad variable names:
      x1 fe2 xbqne
Also bad variable names:
incrementorForMainLoopWhichSpansFromTenToTwenty

createNewMemberIfAgeOverTwentyOneAndMoonIsFull
Avoid describing a value with
  your variable or function
           name.
For example
  isOverEighteen()
might not make sense in
   some countries,
isLegalAge() however
  works everywhere.
Think of your code as a story –
 if readers get stuck because
     of an unpronounceable
 character in your story that
  isn’t part of the main story
  line, give it another, easier
              name.
Avoid globals
Global variables are a terribly
          bad idea.
You run the danger of your
 code being overwritten by
any other JavaScript added to
    the page after yours.
The workaround is to use
closures and the module
        pattern.
var current = null;
var labels = [
   ‘home’:’home’,
   ‘articles’:’articles’,
   ‘contact’:’contact’
];
function init(){
};
function show(){
};
function hide(){
};
var current = null;
                            Everything is global
var labels = [
                            and can be accessed
   ‘home’:’home’,
   ‘articles’:’articles’,
   ‘contact’:’contact’
];
function init(){
};
function show(){
   current = 1;
};
function hide(){
   show();
};
Problem: access is not
 contained, anything in the
page can overwrite what you
            do.
demo = {
                                 Object Literal:
  current:null,
                                  Everything is
  labels:[
                              contained but can be
     ‘home’:’home’,
     ‘articles’:’articles’,
                                accessed via the
     ‘contact’:’contact’
                                 object name.
  ],
  init:function(){
  },
  show:function(){
     demo.current = 1;
  },
  hide:function(){
     demo.show();
  }
}
Problem: Repetition of
module name leads to huge
  code and is annoying.
(function(){
                            Anonymous Module:
  var current = null;
                             Nothing is global.
  var labels = [
     ‘home’:’home’,
     ‘articles’:’articles’,
     ‘contact’:’contact’
  ];
  function init(){
  };
  function show(){
     current = 1;
  };
  function hide(){
     show();
  };
})();
Problem: No access from the
  outside at all (callbacks,
      event handlers)
module = function(){
                                Module Pattern:
  var labels = [
                               You need to specify
     ‘home’:’home’,
     ‘articles’:’articles’,    what is global and
     ‘contact’:’contact’
                              what isn’t – switching
  ];
                               syntax in between.
  return {
     current:null,
     init:function(){
     },
     show:function(){
        module.current = 1;
     },
     hide:function(){
        module.show();
     }
  }
}();
Problem: Repetition of
 module name, different
syntax for inner functions.
module = function(){
                             Revealing Module
  var current = null;
  var labels = [
                                  Pattern:
     ‘home’:’home’,
                              Keep consistent
     ‘articles’:’articles’,
                            syntax and mix and
     ‘contact’:’contact’
  ];
                            match what to make
  function init(){
                                  global.
  };
  function show(){
     current = 1;
  };
  function hide(){
     show();
  };
  return{init:init,show:show,current:current}
}();
module = function(){
                             Revealing Module
  var current = null;
  var labels = [
                                  Pattern:
     ‘home’:’home’,
                              Keep consistent
     ‘articles’:’articles’,
                            syntax and mix and
     ‘contact’:’contact’
  ];
                            match what to make
  function init(){
                                  global.
  };
  function show(){
     current = 1;
  };
  function hide(){
     show();
  };
  return{init:init,show:show,current:current}
}();
module.init();
Stick to a strict coding style
Browsers are very forgiving
    JavaScript parsers.
However, lax coding style will
 hurt you when you shift to
another environment or hand
 over to another developer.
Valid code is good code.
Valid code is secure code.
Validate your code:
http://www.jslint.com/
TextMate users: get Andrew’s
     JavaScript Bundle:
 http://andrewdupont.net/
2006/10/01/javascript-tools-
     textmate-bundle/
Comment as much as needed
      but no more
Comments are messages from
  developer to developer.
“Good code explains itself”
   is an arrogant myth.
Comment what you consider
needed – but don’t tell others
      your life story.
Avoid using the line comment
 though. It is much safer to
  use /* */ as that doesn’t
 cause errors when the line
     break is removed.
If you debug using
comments, there is a nice
        little trick:
module = function(){
   var current = null;
   function init(){
   };
/*
   function show(){
      current = 1;
   };
   function hide(){
      show();
   };
*/
   return{init:init,show:show,current:current}
}();
module = function(){
   var current = null;
   function init(){
   };
/*
   function show(){
      current = 1;
   };
   function hide(){
      show();
   };
// */
   return{init:init,show:show,current:current}
}();
module = function(){
  var current = null;
  function init(){
  };
//*
  function show(){
     current = 1;
  };
  function hide(){
     show();
  };
// */
  return{init:init,show:show,current:current}
}();
Comments can be used to
write documentation – just
    check the YUI doc:
http://yuiblog.com/blog/
   2008/12/08/yuidoc/
However, comments should
never go out to the end user
in plain HTML or JavaScript.
Back to that later :)
Avoid mixing with other
     technologies
JavaScript is good for
 calculation, conversion,
access to outside sources
 (Ajax) and to define the
behaviour of an interface
    (event handling).
Anything else should be kept
to the technology we have to
         do that job.
For example:
Put a red border around all fields 
with a class of “mandatory” when 
they are empty.
var f = document.getElementById('mainform');
var inputs = f.getElementsByTagName('input');
for(var i=0,j=inputs.length;i<j;i++){
  if(inputs[i].className === 'mandatory' &&
     inputs[i].value === ''){
    inputs[i].style.borderColor = '#f00';
    inputs[i].style.borderStyle = 'solid';
    inputs[i].style.borderWidth = '1px';
  }
}
Two month down the line:
All styles have to comply with the 
new company style guide, no 
borders are allowed and errors 
should be shown by an alert icon 
next to the element.
People shouldn’t have to
change your JavaScript code
to change the look and feel.
var f = document.getElementById('mainform');
var inputs = f.getElementsByTagName('input');
for(var i=0,j=inputs.length;i<j;i++){
  if(inputs[i].className === 'mandatory' &&
     inputs[i].value === ''){
    inputs[i].className+=’ error’;
  }
}
Using classes you keep the
 look and feel to the CSS
         designer.
Using CSS inheritance you can
  also avoid having to loop
    over a lot of elements.
Use shortcut notations
Shortcut notations keep your
 code snappy and easier to
read once you got used to it.
var cow = new Object();
cow.colour = ‘white and black’;
cow.breed = ‘Holstein’;
cow.legs = 4;
cow.front = ‘moo’;
cow.bottom = ‘milk’;

             is the same as
var cow = {
   colour:‘white and black’,
   breed:‘Holstein’,
   legs:4,
   front:‘moo’,
   bottom = ‘milk’
};
var lunch = new Array();
lunch[0]=’Dosa’;
lunch[1]=’Roti’;
lunch[2]=’Rice’;
lunch[3]=’what the heck is this?’;

             is the same as
var lunch = [
   ‘Dosa’,
   ‘Roti’,
   ‘Rice’,
   ‘what the heck is this?’
];
if(v){
  var x = v;
} else {
  var x = 10;
}
                is the same as
var x = v || 10;
var direction;
if(x > 100){
  direction = 1;
} else {
  direction = -1;
}
             is the same as
var direction = (x > 100) ? 1 : -1;

/* Avoid nesting these! */
Modularize
Keep your code modularized
      and specialized.
It is very tempting and easy
 to write one function that
       does everything.
As you extend the
   functionality you will
however find that you do the
  same things in several
         functions.
To prevent that, make sure to
write smaller, generic helper
   functions that fulfill one
   specific task rather than
      catch-all methods.
At a later stage you can also
expose these when using the
revealing module pattern to
 create an API to extend the
     main functionality.
Good code should be easy to
build upon without re-writing
          the core.
Enhance progressively
There are things that work on
           the web.
Use these rather than
creating a lot of JavaScript
     dependent code.
DOM generation is slow and
       expensive.
Elements that are dependent
    on JavaScript but are
available when JavaScript is
   turned off are a broken
    promise to our users.
Example: TV tabs.
Tab Interface
Tab Interface
Allow for configuration and
        translation.
Everything that is likely to
change in your code should
not be scattered throughout
          the code.
This includes labels, CSS
classes, IDs and presets.
By putting these into a
  configuration object and
 making this one public we
make maintenance very easy
and allow for customization.
carousel = function(){
  var config = {
    CSS:{
      classes:{
         current:’current’,
         scrollContainer:’scroll’
      },
      IDs:{
         maincontainer:’carousel’
      }
    }
    labels:{
      previous:’back’,
      next:’next’,
      auto:’play’
    }
    settings:{
      amount:5,
skin:’blue’,
        autoplay:false
    }
  };
  function init(){
  };
  function scroll(){
  };
  function highlight(){
  };
  return {config:config,init:init}
}();
Avoid heavy nesting
Code gets unreadable after a
  certain level of nesting –
when is up to your personal
    preference and pain
         threshold.
A really bad idea is to nest
loops inside loops as that also
 means taking care of several
iterator variables (i,j,k,l,m...).
You can avoid heavy nesting
 and loops inside loops with
  specialized tool methods.
function renderProfiles(o){
  var out = document.getElementById(‘profiles’);
  for(var i=0;i<o.members.length;i++){
    var ul = document.createElement(‘ul’);
    var li = document.createElement(‘li’);
    li.appendChild(document.createTextNode(o.members[i].name));
    var nestedul = document.createElement(‘ul’);
    for(var j=0;j<o.members[i].data.length;j++){
      var datali = document.createElement(‘li’);
      datali.appendChild(
         document.createTextNode(
           o.members[i].data[j].label + ‘ ‘ +
           o.members[i].data[j].value
         )
      );
      nestedul.appendChild(datali);
    }
    li.appendChild(nestedul);
  }
  out.appendChild(ul);
}
function renderProfiles(o){
  var out = document.getElementById(‘profiles’);
  for(var i=0;i<o.members.length;i++){
    var ul = document.createElement(‘ul’);
    var li = document.createElement(‘li’);
    li.appendChild(document.createTextNode(data.members[i].name));
    li.appendChild(addMemberData(o.members[i]));
  }
  out.appendChild(ul);
}
function addMemberData(member){
  var ul = document.createElement(‘ul’);
  for(var i=0;i<member.data.length;i++){
    var li = document.createElement(‘li’);
    li.appendChild(
       document.createTextNode(
         member.data[i].label + ‘ ‘ +
         member.data[i].value
       )
    );
  }
  ul.appendChild(li);
  return ul;
}
Think of bad editors and small
           screens.
Optimize loops
Loops can get terribly slow in
        JavaScript.
Most of the time it is because
you’re doing things in them
  that don’t make sense.
var names = ['George','Ringo','Paul','John'];
for(var i=0;i<names.length;i++){
  doSomeThingWith(names[i]);
}
This means that every time
 the loop runs, JavaScript
needs to read the length of
        the array.
You can avoid that by storing
the length value in a different
          variable:
var names = ['George','Ringo','Paul','John'];
var all = names.length;
for(var i=0;i<all;i++){
  doSomeThingWith(names[i]);
}
An even shorter way of
achieving this is to create a
second variable in the pre-
      loop condition.
var names = ['George','Ringo','Paul','John'];
for(var i=0,j=names.length;i<j;i++){
  doSomeThingWith(names[i]);
}
Keep computation-heavy
 code outside of loops.
This includes regular
  expressions but first and
foremost DOM manipulation.
You can create the DOM
nodes in the loop but avoid
  inserting them to the
        document.
Keep DOM access to a
     minimum
If you can avoid it, don’t
     access the DOM.
The reason is that it is slow
  and there are all kind of
browser issues with constant
access to and changes in the
            DOM.
Write or use a helper method
that batch-converts a dataset
          to HTML.
Seed the dataset with as
 much as you can and then
call the method to render all
        out in one go.
Don't yield to browser
        whims!
What works in browsers
today might not tomorrow.
Instead of relying on flaky
  browser behaviour and
hoping it works across the
         board...
...avoid hacking around and
analyze the problem in detail
            instead.
Most of the time you’ll find
the extra functionality you
  need is because of bad
planning of your interface.
Don't trust any data
The most important thing
about good code is that you
 cannot trust any data that
         comes in.
Don’t believe the HTML
 document – any user can
meddle with it for example in
         Firebug.
Don’t trust that data that gets
into your function is the right
format – test with typeof and
  then do something with it.
Don’t expect elements in the
DOM to be available – test for
 them and that they indeed
are what you expect them to
  be before altering them.
And never ever use
   JavaScript to protect
something – it is as easy to
  crack as it is to code :)
Add functionality with
JavaScript, don't create
       content.
If you find yourself creating
   lots and lots of HTML in
  JavaScript, you might be
  doing something wrong.
It is not convenient to create
        using the DOM...
...flaky to use innerHTML (IE’s
  Operation Aborted error)...
...and it is hard to keep track
of the quality of the HTML you
             produce.
If you really have a massive
interface that only should be
available when JavaScript is
          turned on...
...load the interface as a static
    HTML document via Ajax.
That way you keep
maintenance in HTML and
allow for customization.
Build on the shoulders of
          giants
JavaScript is fun, but writing
JavaScript for browsers is less
               so.
JavaScript libraries are
 specifically built to make
browsers behave and your
code more predictable by
 plugging browser holes.
Therefore if you want to write
   code that works without
  keeping the maintenance
         overhead...
... of supporting current
browsers and those to come
          to yourself...
... start with a good library.   (YUI)
Development code is not live
         code.
Last but not least I want you
   to remember that some
  things that work in other
    languages are good in
        JavaScript, too.
Live code is done for
     machines.
Development code is done for
        humans.
Collate, minify and optimize
your code in a build process.
Don’t optimize prematurely
and punish your developers
and those who have to take
      over from them.
If we cut down on the time
 spent coding we have more
     time to perfect the
conversion to machine code.
THANKS!
Keep in touch:
Christian Heilmann
http://wait-till-i.com
http://scriptingenabled.org
http://twitter.com/codepo8




  http://delicious.com/codepo8/jscodetips

More Related Content

What's hot

clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
saber tabatabaee
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
Eyal Vardi
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
JWORKS powered by Ordina
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
Adieu
 
Solid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJSSolid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJS
Rafael Casuso Romate
 
Clean Code
Clean CodeClean Code
Clean Code
Dmytro Turskyi
 
Clean code slide
Clean code slideClean code slide
Clean code slide
Anh Huan Miu
 
Clean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a MonolithClean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a Monolith
Victor Rentea
 
Rust vs C++
Rust vs C++Rust vs C++
Rust vs C++
corehard_by
 
Angular
AngularAngular
Angular
Lilia Sfaxi
 
Clean code
Clean codeClean code
Clean code
ifnu bima
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
ritika1
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflix
Victor Rentea
 
Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code Principles
YeurDreamin'
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
Rob Eisenberg
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass Slides
Nir Kaufman
 
JAVA SCRIPT
JAVA SCRIPTJAVA SCRIPT
JAVA SCRIPT
Go4Guru
 
Modern API Security with JSON Web Tokens
Modern API Security with JSON Web TokensModern API Security with JSON Web Tokens
Modern API Security with JSON Web Tokens
Jonathan LeBlanc
 
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening KeynoteClean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
Victor Rentea
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
WebStackAcademy
 

What's hot (20)

clean code book summary - uncle bob - English version
clean code book summary - uncle bob - English versionclean code book summary - uncle bob - English version
clean code book summary - uncle bob - English version
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Solid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJSSolid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJS
 
Clean Code
Clean CodeClean Code
Clean Code
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
Clean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a MonolithClean Pragmatic Architecture - Avoiding a Monolith
Clean Pragmatic Architecture - Avoiding a Monolith
 
Rust vs C++
Rust vs C++Rust vs C++
Rust vs C++
 
Angular
AngularAngular
Angular
 
Clean code
Clean codeClean code
Clean code
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflix
 
Clean Code Principles
Clean Code PrinciplesClean Code Principles
Clean Code Principles
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass Slides
 
JAVA SCRIPT
JAVA SCRIPTJAVA SCRIPT
JAVA SCRIPT
 
Modern API Security with JSON Web Tokens
Modern API Security with JSON Web TokensModern API Security with JSON Web Tokens
Modern API Security with JSON Web Tokens
 
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening KeynoteClean Code @Voxxed Days Cluj 2023 - opening Keynote
Clean Code @Voxxed Days Cluj 2023 - opening Keynote
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 

Viewers also liked

Mysql Crud, Php Mysql, php, sql
Mysql Crud, Php Mysql, php, sqlMysql Crud, Php Mysql, php, sql
Mysql Crud, Php Mysql, php, sql
Aimal Miakhel
 
Advanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JSAdvanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JS
Simon Guest
 
PHP - Introduction to PHP MySQL Joins and SQL Functions
PHP -  Introduction to PHP MySQL Joins and SQL FunctionsPHP -  Introduction to PHP MySQL Joins and SQL Functions
PHP - Introduction to PHP MySQL Joins and SQL Functions
Vibrant Technologies & Computers
 
Top 100 PHP Questions and Answers
Top 100 PHP Questions and AnswersTop 100 PHP Questions and Answers
Top 100 PHP Questions and Answers
iimjobs and hirist
 
CodeIgniter 101 Tutorial
CodeIgniter 101 TutorialCodeIgniter 101 Tutorial
CodeIgniter 101 Tutorial
Konstantinos Magarisiotis
 
Codeigniter
CodeigniterCodeigniter
Codeigniter
minhrau111
 
Building RESTtful services in MEAN
Building RESTtful services in MEANBuilding RESTtful services in MEAN
Building RESTtful services in MEAN
Madhukara Phatak
 

Viewers also liked (7)

Mysql Crud, Php Mysql, php, sql
Mysql Crud, Php Mysql, php, sqlMysql Crud, Php Mysql, php, sql
Mysql Crud, Php Mysql, php, sql
 
Advanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JSAdvanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JS
 
PHP - Introduction to PHP MySQL Joins and SQL Functions
PHP -  Introduction to PHP MySQL Joins and SQL FunctionsPHP -  Introduction to PHP MySQL Joins and SQL Functions
PHP - Introduction to PHP MySQL Joins and SQL Functions
 
Top 100 PHP Questions and Answers
Top 100 PHP Questions and AnswersTop 100 PHP Questions and Answers
Top 100 PHP Questions and Answers
 
CodeIgniter 101 Tutorial
CodeIgniter 101 TutorialCodeIgniter 101 Tutorial
CodeIgniter 101 Tutorial
 
Codeigniter
CodeigniterCodeigniter
Codeigniter
 
Building RESTtful services in MEAN
Building RESTtful services in MEANBuilding RESTtful services in MEAN
Building RESTtful services in MEAN
 

Similar to Javascript Best Practices

HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
David Padbury
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
ciklum_ods
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
Hoat Le
 
LISA Qooxdoo Tutorial Handouts
LISA Qooxdoo Tutorial HandoutsLISA Qooxdoo Tutorial Handouts
LISA Qooxdoo Tutorial Handouts
Tobias Oetiker
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
Ran Mizrahi
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
kaven yan
 
"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson
GWTcon
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
intelliyole
 
Modular javascript
Modular javascriptModular javascript
Modular javascript
Zain Shaikh
 
Robots in Swift
Robots in SwiftRobots in Swift
Robots in Swift
Janie Clayton
 
Thinking In Swift
Thinking In SwiftThinking In Swift
Thinking In Swift
Janie Clayton
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introduction
Birol Efe
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
Leonid Maslov
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.
Alberto Naranjo
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
Guillaume Laforge
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
Amal Khailtash
 
The cost of learning - advantage of mixer2
The cost of learning - advantage of mixer2The cost of learning - advantage of mixer2
The cost of learning - advantage of mixer2
Y Watanabe
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
Dominic Arrojado
 

Similar to Javascript Best Practices (20)

HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
LISA Qooxdoo Tutorial Handouts
LISA Qooxdoo Tutorial HandoutsLISA Qooxdoo Tutorial Handouts
LISA Qooxdoo Tutorial Handouts
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
 
Modular javascript
Modular javascriptModular javascript
Modular javascript
 
Robots in Swift
Robots in SwiftRobots in Swift
Robots in Swift
 
Thinking In Swift
Thinking In SwiftThinking In Swift
Thinking In Swift
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introduction
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.Javascript quiz. Questions to ask when recruiting developers.
Javascript quiz. Questions to ask when recruiting developers.
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 
The cost of learning - advantage of mixer2
The cost of learning - advantage of mixer2The cost of learning - advantage of mixer2
The cost of learning - advantage of mixer2
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 

More from Christian Heilmann

Develop, Debug, Learn? - Dotjs2019
Develop, Debug, Learn? - Dotjs2019Develop, Debug, Learn? - Dotjs2019
Develop, Debug, Learn? - Dotjs2019
Christian Heilmann
 
Hinting at a better web
Hinting at a better webHinting at a better web
Hinting at a better web
Christian Heilmann
 
Taking the "vile" out of privilege
Taking the "vile" out of privilegeTaking the "vile" out of privilege
Taking the "vile" out of privilege
Christian Heilmann
 
Seven ways to be a happier JavaScript developer - NDC Oslo
Seven ways to be a happier JavaScript developer - NDC OsloSeven ways to be a happier JavaScript developer - NDC Oslo
Seven ways to be a happier JavaScript developer - NDC Oslo
Christian Heilmann
 
Artificial intelligence for humans… #AIDC2018 keynote
Artificial intelligence for humans… #AIDC2018 keynoteArtificial intelligence for humans… #AIDC2018 keynote
Artificial intelligence for humans… #AIDC2018 keynote
Christian Heilmann
 
Killing the golden calf of coding - We are Developers keynote
Killing the golden calf of coding - We are Developers keynoteKilling the golden calf of coding - We are Developers keynote
Killing the golden calf of coding - We are Developers keynote
Christian Heilmann
 
Progressive Web Apps - Techdays Finland
Progressive Web Apps - Techdays FinlandProgressive Web Apps - Techdays Finland
Progressive Web Apps - Techdays Finland
Christian Heilmann
 
Taking the "vile" out of privilege
Taking the "vile" out of privilegeTaking the "vile" out of privilege
Taking the "vile" out of privilege
Christian Heilmann
 
Five ways to be a happier JavaScript developer
Five ways to be a happier JavaScript developerFive ways to be a happier JavaScript developer
Five ways to be a happier JavaScript developer
Christian Heilmann
 
Taking the P out of PWA
Taking the P out of PWATaking the P out of PWA
Taking the P out of PWA
Christian Heilmann
 
Sacrificing the golden calf of "coding"
Sacrificing the golden calf of "coding"Sacrificing the golden calf of "coding"
Sacrificing the golden calf of "coding"
Christian Heilmann
 
You learned JavaScript - now what?
You learned JavaScript - now what?You learned JavaScript - now what?
You learned JavaScript - now what?
Christian Heilmann
 
Sacrificing the golden calf of "coding"
Sacrificing the golden calf of "coding"Sacrificing the golden calf of "coding"
Sacrificing the golden calf of "coding"
Christian Heilmann
 
Progressive Web Apps - Covering the best of both worlds - DevReach
Progressive Web Apps - Covering the best of both worlds - DevReachProgressive Web Apps - Covering the best of both worlds - DevReach
Progressive Web Apps - Covering the best of both worlds - DevReach
Christian Heilmann
 
Progressive Web Apps - Covering the best of both worlds
Progressive Web Apps - Covering the best of both worldsProgressive Web Apps - Covering the best of both worlds
Progressive Web Apps - Covering the best of both worlds
Christian Heilmann
 
Non-trivial pursuits: Learning machines and forgetful humans
Non-trivial pursuits: Learning machines and forgetful humansNon-trivial pursuits: Learning machines and forgetful humans
Non-trivial pursuits: Learning machines and forgetful humans
Christian Heilmann
 
Progressive Web Apps - Bringing the web front and center
Progressive Web Apps - Bringing the web front and center Progressive Web Apps - Bringing the web front and center
Progressive Web Apps - Bringing the web front and center
Christian Heilmann
 
CSS vs. JavaScript - Trust vs. Control
CSS vs. JavaScript - Trust vs. ControlCSS vs. JavaScript - Trust vs. Control
CSS vs. JavaScript - Trust vs. Control
Christian Heilmann
 
Leveling up your JavaScipt - DrupalJam 2017
Leveling up your JavaScipt - DrupalJam 2017Leveling up your JavaScipt - DrupalJam 2017
Leveling up your JavaScipt - DrupalJam 2017
Christian Heilmann
 
The Soul in The Machine - Developing for Humans (FrankenJS edition)
The Soul in The Machine - Developing for Humans (FrankenJS edition)The Soul in The Machine - Developing for Humans (FrankenJS edition)
The Soul in The Machine - Developing for Humans (FrankenJS edition)
Christian Heilmann
 

More from Christian Heilmann (20)

Develop, Debug, Learn? - Dotjs2019
Develop, Debug, Learn? - Dotjs2019Develop, Debug, Learn? - Dotjs2019
Develop, Debug, Learn? - Dotjs2019
 
Hinting at a better web
Hinting at a better webHinting at a better web
Hinting at a better web
 
Taking the "vile" out of privilege
Taking the "vile" out of privilegeTaking the "vile" out of privilege
Taking the "vile" out of privilege
 
Seven ways to be a happier JavaScript developer - NDC Oslo
Seven ways to be a happier JavaScript developer - NDC OsloSeven ways to be a happier JavaScript developer - NDC Oslo
Seven ways to be a happier JavaScript developer - NDC Oslo
 
Artificial intelligence for humans… #AIDC2018 keynote
Artificial intelligence for humans… #AIDC2018 keynoteArtificial intelligence for humans… #AIDC2018 keynote
Artificial intelligence for humans… #AIDC2018 keynote
 
Killing the golden calf of coding - We are Developers keynote
Killing the golden calf of coding - We are Developers keynoteKilling the golden calf of coding - We are Developers keynote
Killing the golden calf of coding - We are Developers keynote
 
Progressive Web Apps - Techdays Finland
Progressive Web Apps - Techdays FinlandProgressive Web Apps - Techdays Finland
Progressive Web Apps - Techdays Finland
 
Taking the "vile" out of privilege
Taking the "vile" out of privilegeTaking the "vile" out of privilege
Taking the "vile" out of privilege
 
Five ways to be a happier JavaScript developer
Five ways to be a happier JavaScript developerFive ways to be a happier JavaScript developer
Five ways to be a happier JavaScript developer
 
Taking the P out of PWA
Taking the P out of PWATaking the P out of PWA
Taking the P out of PWA
 
Sacrificing the golden calf of "coding"
Sacrificing the golden calf of "coding"Sacrificing the golden calf of "coding"
Sacrificing the golden calf of "coding"
 
You learned JavaScript - now what?
You learned JavaScript - now what?You learned JavaScript - now what?
You learned JavaScript - now what?
 
Sacrificing the golden calf of "coding"
Sacrificing the golden calf of "coding"Sacrificing the golden calf of "coding"
Sacrificing the golden calf of "coding"
 
Progressive Web Apps - Covering the best of both worlds - DevReach
Progressive Web Apps - Covering the best of both worlds - DevReachProgressive Web Apps - Covering the best of both worlds - DevReach
Progressive Web Apps - Covering the best of both worlds - DevReach
 
Progressive Web Apps - Covering the best of both worlds
Progressive Web Apps - Covering the best of both worldsProgressive Web Apps - Covering the best of both worlds
Progressive Web Apps - Covering the best of both worlds
 
Non-trivial pursuits: Learning machines and forgetful humans
Non-trivial pursuits: Learning machines and forgetful humansNon-trivial pursuits: Learning machines and forgetful humans
Non-trivial pursuits: Learning machines and forgetful humans
 
Progressive Web Apps - Bringing the web front and center
Progressive Web Apps - Bringing the web front and center Progressive Web Apps - Bringing the web front and center
Progressive Web Apps - Bringing the web front and center
 
CSS vs. JavaScript - Trust vs. Control
CSS vs. JavaScript - Trust vs. ControlCSS vs. JavaScript - Trust vs. Control
CSS vs. JavaScript - Trust vs. Control
 
Leveling up your JavaScipt - DrupalJam 2017
Leveling up your JavaScipt - DrupalJam 2017Leveling up your JavaScipt - DrupalJam 2017
Leveling up your JavaScipt - DrupalJam 2017
 
The Soul in The Machine - Developing for Humans (FrankenJS edition)
The Soul in The Machine - Developing for Humans (FrankenJS edition)The Soul in The Machine - Developing for Humans (FrankenJS edition)
The Soul in The Machine - Developing for Humans (FrankenJS edition)
 

Recently uploaded

Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
SitimaJohn
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdfAI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
Techgropse Pvt.Ltd.
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
Claudio Di Ciccio
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Things to Consider When Choosing a Website Developer for your Website | FODUU
Things to Consider When Choosing a Website Developer for your Website | FODUUThings to Consider When Choosing a Website Developer for your Website | FODUU
Things to Consider When Choosing a Website Developer for your Website | FODUU
FODUU
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
Daiki Mogmet Ito
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 

Recently uploaded (20)

Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdfAI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”“I’m still / I’m still / Chaining from the Block”
“I’m still / I’m still / Chaining from the Block”
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Things to Consider When Choosing a Website Developer for your Website | FODUU
Things to Consider When Choosing a Website Developer for your Website | FODUUThings to Consider When Choosing a Website Developer for your Website | FODUU
Things to Consider When Choosing a Website Developer for your Website | FODUU
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
How to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For FlutterHow to use Firebase Data Connect For Flutter
How to use Firebase Data Connect For Flutter
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 

Javascript Best Practices

  • 1. JavaScript “Best Practices” Christian Heilmann | http://wait-till-i.com | http://scriptingenabled.org Bangalore, India, Yahoo internal training, February 2009
  • 3. Trying to tell developers to change their ways and follow your example is a tough call.
  • 4. I also consider it a flawed process.
  • 5. I am bored of discussions of syntax details.
  • 6. This is not about forcing you to believe what I believe.
  • 7. This is about telling you what worked for me and might as well work for you.
  • 8. I’ve collected a lot of ideas and tips over time how to be more effective.
  • 9. Avoid heavy nesting Make it understandable Optimize loops Avoid globals Keep DOM access to a Stick to a strict coding style minimum Comment as much as needed Don't yield to browser whims but not more Don't trust any data Avoid mixing with other technologies Add functionality with JavaScript, not content Use shortcut notations Build on the shoulders of Modularize giants Enhance progressively Development code is not live Allow for configuration and code translation
  • 11. Choose easy to understand and short names for variables and functions.
  • 12. Bad variable names: x1 fe2 xbqne
  • 13. Also bad variable names: incrementorForMainLoopWhichSpansFromTenToTwenty createNewMemberIfAgeOverTwentyOneAndMoonIsFull
  • 14. Avoid describing a value with your variable or function name.
  • 15. For example isOverEighteen() might not make sense in some countries, isLegalAge() however works everywhere.
  • 16. Think of your code as a story – if readers get stuck because of an unpronounceable character in your story that isn’t part of the main story line, give it another, easier name.
  • 18. Global variables are a terribly bad idea.
  • 19. You run the danger of your code being overwritten by any other JavaScript added to the page after yours.
  • 20. The workaround is to use closures and the module pattern.
  • 21. var current = null; var labels = [ ‘home’:’home’, ‘articles’:’articles’, ‘contact’:’contact’ ]; function init(){ }; function show(){ }; function hide(){ };
  • 22. var current = null; Everything is global var labels = [ and can be accessed ‘home’:’home’, ‘articles’:’articles’, ‘contact’:’contact’ ]; function init(){ }; function show(){ current = 1; }; function hide(){ show(); };
  • 23. Problem: access is not contained, anything in the page can overwrite what you do.
  • 24. demo = { Object Literal: current:null, Everything is labels:[ contained but can be ‘home’:’home’, ‘articles’:’articles’, accessed via the ‘contact’:’contact’ object name. ], init:function(){ }, show:function(){ demo.current = 1; }, hide:function(){ demo.show(); } }
  • 25. Problem: Repetition of module name leads to huge code and is annoying.
  • 26. (function(){ Anonymous Module: var current = null; Nothing is global. var labels = [ ‘home’:’home’, ‘articles’:’articles’, ‘contact’:’contact’ ]; function init(){ }; function show(){ current = 1; }; function hide(){ show(); }; })();
  • 27. Problem: No access from the outside at all (callbacks, event handlers)
  • 28. module = function(){ Module Pattern: var labels = [ You need to specify ‘home’:’home’, ‘articles’:’articles’, what is global and ‘contact’:’contact’ what isn’t – switching ]; syntax in between. return { current:null, init:function(){ }, show:function(){ module.current = 1; }, hide:function(){ module.show(); } } }();
  • 29. Problem: Repetition of module name, different syntax for inner functions.
  • 30. module = function(){ Revealing Module var current = null; var labels = [ Pattern: ‘home’:’home’, Keep consistent ‘articles’:’articles’, syntax and mix and ‘contact’:’contact’ ]; match what to make function init(){ global. }; function show(){ current = 1; }; function hide(){ show(); }; return{init:init,show:show,current:current} }();
  • 31. module = function(){ Revealing Module var current = null; var labels = [ Pattern: ‘home’:’home’, Keep consistent ‘articles’:’articles’, syntax and mix and ‘contact’:’contact’ ]; match what to make function init(){ global. }; function show(){ current = 1; }; function hide(){ show(); }; return{init:init,show:show,current:current} }(); module.init();
  • 32. Stick to a strict coding style
  • 33. Browsers are very forgiving JavaScript parsers.
  • 34. However, lax coding style will hurt you when you shift to another environment or hand over to another developer.
  • 35. Valid code is good code.
  • 36. Valid code is secure code.
  • 38. TextMate users: get Andrew’s JavaScript Bundle: http://andrewdupont.net/ 2006/10/01/javascript-tools- textmate-bundle/
  • 39. Comment as much as needed but no more
  • 40. Comments are messages from developer to developer.
  • 41. “Good code explains itself” is an arrogant myth.
  • 42. Comment what you consider needed – but don’t tell others your life story.
  • 43. Avoid using the line comment though. It is much safer to use /* */ as that doesn’t cause errors when the line break is removed.
  • 44. If you debug using comments, there is a nice little trick:
  • 45. module = function(){ var current = null; function init(){ }; /* function show(){ current = 1; }; function hide(){ show(); }; */ return{init:init,show:show,current:current} }();
  • 46. module = function(){ var current = null; function init(){ }; /* function show(){ current = 1; }; function hide(){ show(); }; // */ return{init:init,show:show,current:current} }();
  • 47. module = function(){ var current = null; function init(){ }; //* function show(){ current = 1; }; function hide(){ show(); }; // */ return{init:init,show:show,current:current} }();
  • 48. Comments can be used to write documentation – just check the YUI doc: http://yuiblog.com/blog/ 2008/12/08/yuidoc/
  • 49. However, comments should never go out to the end user in plain HTML or JavaScript.
  • 50. Back to that later :)
  • 51. Avoid mixing with other technologies
  • 52. JavaScript is good for calculation, conversion, access to outside sources (Ajax) and to define the behaviour of an interface (event handling).
  • 53. Anything else should be kept to the technology we have to do that job.
  • 55. var f = document.getElementById('mainform'); var inputs = f.getElementsByTagName('input'); for(var i=0,j=inputs.length;i<j;i++){ if(inputs[i].className === 'mandatory' && inputs[i].value === ''){ inputs[i].style.borderColor = '#f00'; inputs[i].style.borderStyle = 'solid'; inputs[i].style.borderWidth = '1px'; } }
  • 56. Two month down the line: All styles have to comply with the  new company style guide, no  borders are allowed and errors  should be shown by an alert icon  next to the element.
  • 57. People shouldn’t have to change your JavaScript code to change the look and feel.
  • 58. var f = document.getElementById('mainform'); var inputs = f.getElementsByTagName('input'); for(var i=0,j=inputs.length;i<j;i++){ if(inputs[i].className === 'mandatory' && inputs[i].value === ''){ inputs[i].className+=’ error’; } }
  • 59. Using classes you keep the look and feel to the CSS designer.
  • 60. Using CSS inheritance you can also avoid having to loop over a lot of elements.
  • 62. Shortcut notations keep your code snappy and easier to read once you got used to it.
  • 63. var cow = new Object(); cow.colour = ‘white and black’; cow.breed = ‘Holstein’; cow.legs = 4; cow.front = ‘moo’; cow.bottom = ‘milk’; is the same as var cow = { colour:‘white and black’, breed:‘Holstein’, legs:4, front:‘moo’, bottom = ‘milk’ };
  • 64. var lunch = new Array(); lunch[0]=’Dosa’; lunch[1]=’Roti’; lunch[2]=’Rice’; lunch[3]=’what the heck is this?’; is the same as var lunch = [ ‘Dosa’, ‘Roti’, ‘Rice’, ‘what the heck is this?’ ];
  • 65. if(v){ var x = v; } else { var x = 10; } is the same as var x = v || 10;
  • 66. var direction; if(x > 100){ direction = 1; } else { direction = -1; } is the same as var direction = (x > 100) ? 1 : -1; /* Avoid nesting these! */
  • 68. Keep your code modularized and specialized.
  • 69. It is very tempting and easy to write one function that does everything.
  • 70. As you extend the functionality you will however find that you do the same things in several functions.
  • 71. To prevent that, make sure to write smaller, generic helper functions that fulfill one specific task rather than catch-all methods.
  • 72. At a later stage you can also expose these when using the revealing module pattern to create an API to extend the main functionality.
  • 73. Good code should be easy to build upon without re-writing the core.
  • 75. There are things that work on the web.
  • 76. Use these rather than creating a lot of JavaScript dependent code.
  • 77. DOM generation is slow and expensive.
  • 78. Elements that are dependent on JavaScript but are available when JavaScript is turned off are a broken promise to our users.
  • 82. Allow for configuration and translation.
  • 83. Everything that is likely to change in your code should not be scattered throughout the code.
  • 84. This includes labels, CSS classes, IDs and presets.
  • 85. By putting these into a configuration object and making this one public we make maintenance very easy and allow for customization.
  • 86. carousel = function(){ var config = { CSS:{ classes:{ current:’current’, scrollContainer:’scroll’ }, IDs:{ maincontainer:’carousel’ } } labels:{ previous:’back’, next:’next’, auto:’play’ } settings:{ amount:5,
  • 87. skin:’blue’, autoplay:false } }; function init(){ }; function scroll(){ }; function highlight(){ }; return {config:config,init:init} }();
  • 89. Code gets unreadable after a certain level of nesting – when is up to your personal preference and pain threshold.
  • 90. A really bad idea is to nest loops inside loops as that also means taking care of several iterator variables (i,j,k,l,m...).
  • 91. You can avoid heavy nesting and loops inside loops with specialized tool methods.
  • 92. function renderProfiles(o){ var out = document.getElementById(‘profiles’); for(var i=0;i<o.members.length;i++){ var ul = document.createElement(‘ul’); var li = document.createElement(‘li’); li.appendChild(document.createTextNode(o.members[i].name)); var nestedul = document.createElement(‘ul’); for(var j=0;j<o.members[i].data.length;j++){ var datali = document.createElement(‘li’); datali.appendChild( document.createTextNode( o.members[i].data[j].label + ‘ ‘ + o.members[i].data[j].value ) ); nestedul.appendChild(datali); } li.appendChild(nestedul); } out.appendChild(ul); }
  • 93. function renderProfiles(o){ var out = document.getElementById(‘profiles’); for(var i=0;i<o.members.length;i++){ var ul = document.createElement(‘ul’); var li = document.createElement(‘li’); li.appendChild(document.createTextNode(data.members[i].name)); li.appendChild(addMemberData(o.members[i])); } out.appendChild(ul); } function addMemberData(member){ var ul = document.createElement(‘ul’); for(var i=0;i<member.data.length;i++){ var li = document.createElement(‘li’); li.appendChild( document.createTextNode( member.data[i].label + ‘ ‘ + member.data[i].value ) ); } ul.appendChild(li); return ul; }
  • 94. Think of bad editors and small screens.
  • 96. Loops can get terribly slow in JavaScript.
  • 97. Most of the time it is because you’re doing things in them that don’t make sense.
  • 98. var names = ['George','Ringo','Paul','John']; for(var i=0;i<names.length;i++){ doSomeThingWith(names[i]); }
  • 99. This means that every time the loop runs, JavaScript needs to read the length of the array.
  • 100. You can avoid that by storing the length value in a different variable:
  • 101. var names = ['George','Ringo','Paul','John']; var all = names.length; for(var i=0;i<all;i++){ doSomeThingWith(names[i]); }
  • 102. An even shorter way of achieving this is to create a second variable in the pre- loop condition.
  • 103. var names = ['George','Ringo','Paul','John']; for(var i=0,j=names.length;i<j;i++){ doSomeThingWith(names[i]); }
  • 104. Keep computation-heavy code outside of loops.
  • 105. This includes regular expressions but first and foremost DOM manipulation.
  • 106. You can create the DOM nodes in the loop but avoid inserting them to the document.
  • 107. Keep DOM access to a minimum
  • 108. If you can avoid it, don’t access the DOM.
  • 109. The reason is that it is slow and there are all kind of browser issues with constant access to and changes in the DOM.
  • 110. Write or use a helper method that batch-converts a dataset to HTML.
  • 111. Seed the dataset with as much as you can and then call the method to render all out in one go.
  • 112. Don't yield to browser whims!
  • 113. What works in browsers today might not tomorrow.
  • 114. Instead of relying on flaky browser behaviour and hoping it works across the board...
  • 115. ...avoid hacking around and analyze the problem in detail instead.
  • 116. Most of the time you’ll find the extra functionality you need is because of bad planning of your interface.
  • 118. The most important thing about good code is that you cannot trust any data that comes in.
  • 119. Don’t believe the HTML document – any user can meddle with it for example in Firebug.
  • 120. Don’t trust that data that gets into your function is the right format – test with typeof and then do something with it.
  • 121. Don’t expect elements in the DOM to be available – test for them and that they indeed are what you expect them to be before altering them.
  • 122. And never ever use JavaScript to protect something – it is as easy to crack as it is to code :)
  • 123. Add functionality with JavaScript, don't create content.
  • 124. If you find yourself creating lots and lots of HTML in JavaScript, you might be doing something wrong.
  • 125. It is not convenient to create using the DOM...
  • 126. ...flaky to use innerHTML (IE’s Operation Aborted error)...
  • 127. ...and it is hard to keep track of the quality of the HTML you produce.
  • 128. If you really have a massive interface that only should be available when JavaScript is turned on...
  • 129. ...load the interface as a static HTML document via Ajax.
  • 130. That way you keep maintenance in HTML and allow for customization.
  • 131. Build on the shoulders of giants
  • 132. JavaScript is fun, but writing JavaScript for browsers is less so.
  • 133. JavaScript libraries are specifically built to make browsers behave and your code more predictable by plugging browser holes.
  • 134. Therefore if you want to write code that works without keeping the maintenance overhead...
  • 135. ... of supporting current browsers and those to come to yourself...
  • 136. ... start with a good library. (YUI)
  • 137. Development code is not live code.
  • 138. Last but not least I want you to remember that some things that work in other languages are good in JavaScript, too.
  • 139. Live code is done for machines.
  • 140. Development code is done for humans.
  • 141. Collate, minify and optimize your code in a build process.
  • 142. Don’t optimize prematurely and punish your developers and those who have to take over from them.
  • 143. If we cut down on the time spent coding we have more time to perfect the conversion to machine code.
  • 144.
  • 145. THANKS! Keep in touch: Christian Heilmann http://wait-till-i.com http://scriptingenabled.org http://twitter.com/codepo8 http://delicious.com/codepo8/jscodetips