IT depends.webdeveloper's notes by MichaƂ Fikus

Skip to content

JavaScript basics every developer should know – part I

I bet every developer who has been working for some time in front-end had to deal with JavaScript at least a little. Even back-end guys have to deal with JS sometimes – maybe they do not write fancy applications but quite often there is a need to make some small script to manipulate dom. Especially now when AJAX is a must-be.

The problem is that by doing this unexperienced developer may cause some serious and hard to detect errors. Sources may differ – from browsers inconsistencies to JavaScripts tricky nature.

Here are some most common issues you should keep in mind while JavaScripting:

  1. respect global namespace
  2. avoid global variables, functions (local are faster and safer)
  3. learn about closures but use them sparingly (performance matters)
  4. CDATE you code with comments (to make older browsers happy, in XHTML)
    <script type="text/javascript">
    /* <!CDATA[ */
    // your script
    /* ]]> */
    </script>
  5. check if DOM element exists before taking action on it (otherwise error may occur)
    var element = document.getElementById('breadcrumbs');
    
    if(element)
    {
        // do some magic
    }
  6. var a = []; is better (= faster and safer) than var a = new Array(); (new Array calls a constructor and may be overwritten)
  7. inline styling is evil. Even in JS. However
    element.style.fontWeight = 'bold';

    is better than

    element.setAttribute('style', 'font-weight:bold');

    which is slower and breaks in IE. Adding class is the best.

This entry was posted in Webdevelopment basics and tagged , . Bookmark the permalink.

Leave a Reply

Required fields are marked *