[Cheat Sheet] Javascript – Best practices and performance

Note: This is part of Javascript learning roadmap.

  • Variable and function naming
    • variables should be nouns (‘car’, ‘survey’)
    • function names should begin with a verb (‘getName()’)
    • boolean function should start with if + what we check (‘isEnabled()’)
  • Variable type transparency
    • indicate the type of variable to avoid confusion (first one is ok, the rest not so used but is good to recognize them)
    • at initialization
      • var found = false // boolean
      • var count = -1 // number
    • Hungarian notation – add letter (s – string, b – boolean, n – number, o – object) in front of identifier
      • var bEnabled; // boolean
      • var iCount; // number
      • var sName; // string 
    • use type comments
      • var found /* Boolean */ = false
  • Decouple HTML/JS 
    • user script in separate file
    • avoid using html in js code (set innerHTML)
  • Decouple CSS/JS 
    • avoid setting style in JS – set class instead (element.className) – this improves performance as well because it will trigger one reflow/repaint instead of one per each property changed
  • Decouple Application Logic / Event Handlers
    • event handlers should only retrieve the required data from event param and call a separate action in application logic
    • event param should not be send to the app logic (just the necessary information)
    • the action from the app logic should work just as fine if it is triggered in other way (other event or programmatically)
  • Respect object ownership – don’t change the behavior/form of an object you didn’t create
    • don’t add properties to instances or prototypes
    • don’t add methods to instances or prototypes
    • don’t redefine existing methods
  • Avoid globals
    • looking trough a scope chain to find a global variable takes time (global lookups)
    • if you’re using a global object, get the reference in the local scope first
  • Avoid null comparasion 
    • for clarity, object should be checked for what they should be, not what they shouldn’t be
    • if value is reference type -> use instanceof
    • if value is primitive type -> use typeof
    • if expecting a method name  -> check the existance with typeof
  • Use constants 
    • avoid hard-coded strings as urls or error messages
  • Optimize loops 
    • decrement iterators – faster than increment
    • simplify the terminal condition (is executed every time)
      • ex. instead of getting array.length each time -> get the length in a local variable first (especially when performing on a HtmlCollection which makes a querry on the document each time)
    • simplify the loop value
  • Avoid double interpretation – writing JS code as string which will be interpreted twice (in eval() or when creating a function with body as string
  • Native methods are fast – written in compiled languages c/c++ (ex. use Math. for mathematical operation)
  • Switch is faster than if-else – to better optimize, put the cases in order from the most likely to least likely
  • Minimize statement count 
    • the number of statements in JS code affects the speed with which the operations are performed
    • a single statement can complete multiple operations faster than multiple statements each performing one operation
    • ex. use one statement to declare more variables (var i = 4, c = 2, isTrue = true;)
    • ex. use iterative values (var name = a[i++]; instead of var name = a[i]; i++; )
    • ex. use array and object literals
  • Minimize DOM interactions 
    • minimize live updates
      • avoid updating the DOM in loops
      • maybe create a fragment in loop -> append it at the end
      • innerHTML is faster than appendChild() / createElement()
      • use Event Delegation – add one event handler on the most high in hierarchy common ancestor (document) and delegate the event to each specific element (using event.target.id)
      • avoid accessing HtmlCollection to many times – especially in loops

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s