Refactoring javascript : managing existing js code

As an web developer we always have so many problems regarding Javascript as our lines of codes in our app grow. The root cause of these problems are

  • There are so many files. In any of the files you might have missing semicolons, or used undefined variables
  • You often forget to put var before variable declaration, and this put the variable in the global scope
    • This variable might conflict with same variable name you used in other part of your code.


  $(function () {
    if ($('body.shares').length == 0 && $('body.pact_profile_page').length == 0)  return false;

  // Basic syntax would be
  $(document).ready(function () {
    var target_element_is_not_loaded = ($('.your-target-selector').length > 0);
    if (target_element_is_not_loaded) return false;

The basic idea is, you only execute your code if your targeted page is loaded. Means if your JS code is meant for posts page then you do not need to load this code else where.


Other Links


TDD : Why Red Green Refactor is important in TDD

As a TDD practitioner I feel that the first phase (Red) is very important to know that the problem you are trying to solve has not already been solved. And it worth starting to write production code. Other wise you might not know your code did that job or you code is redundant.

RGF teaches you the law of nature. You need to identify the problem before solving the problem. Red (exit code non zero) indicates that you have identified the problem area and now you need to solve it.

After the problem is solved, then you can refactor/improve the way you solved. May be you find you a better and efficient way to reach the destination.