User:Jesdisciple/Manual of Style

From Wikibooks, open books for an open world
Jump to navigation Jump to search

This is a list of things to avoid in the JavaScript book.

  • Implicitly global variables.
  • Wrong:
function foo(){
   bar = 1
}
  • Right:
function foo(){
    var bar = 1
    
    // Or if you really want the global one:
    window.bar = 1
}
  • Inline event handlers.
  • Wrong:
<html>
    <body>
        <div onclick="alert('*headdesk*');">
            This is wrong!
        </div>
    </body>
</html>
  • Right:
<html>
    <head>
        <script type="text/javascript">
            window.onload = function (){
                document.getElementById('foo').onclick = function (){
                    alert('The Force is strong with this one.');
                };
            };
        </script>
    </head>
    <body>
        <div id="foo">
            This is right!
        </div>
    </body>
</html>
  • Looping through an array with for..in. Arrays only have anything special about them for numeric indices. Use an object if not all of your indices are numeric. Array.prototype was made to be modified, but the type was not made to be associative.