Coding Standards & Best Practices : Javascript

Javascript

Naming Conventions

  • All variables to be written in camel case. Ex: windowHeight
  • All Class Names / Module Names in capitalized. Ex: SampleModule
  • Namespaces in uppercase. ex: SF
  • Custom jQuery object variables prefixed with $. ex: $fooDiv

Best practices

  • Avoid inline javascripts
  • Avoid including your javascript libraries in header tags

    This may impact your initial view perceivance

  • Avoid styling elements via javascript.

    Instead use classes if the properties are not dynamic.

  • Declare variables at the begining of your function
  • Keep the cyclomatic complexity as low as possible( no more than 10)
  • Avoid too many nested if else statements – This might add to cyclomatic complexity of your program
  • Use /^\s*$/ regex to check blank string.
  • Define base when using parseInt

    Not defining base may result in unexpected behavior.

    Good use

    parseInt(0048, 10) // results 48
  • Maximize no of pure functions

    Pure functions are more consistent and are great for reusability. While creating a reusable library such as services, utility functions pure function helps to make code more cleaner.

jQuery Best practices

  • Delegate events if your component has dynamic elements.
  • Minimize selector length while delegating events.
  • Make use of chaining when ever possible
  • Cache dom objects to improve performance
  • Avoid $.each when ever possible.
  • Check for element/module existance before initializing events on it childs. This would avoid errors and unnecessary code execution.