6 Simple Tips to Immediately Improve Your JavaScript

1: Stop Using $(document).ready()

Not Bad

<head>
    <script type="text/javascript">
        $(document).ready(function () {
            // Do stuff.
        });
    </script>
</head>

Better


        <script type="text/javascript">
            // Self executing function
            (function(){
                // Do stuff.
            })();
        </script>
    </body>
</html>

2: Use Strict

function () {
  "use strict";
  // Do some stuff
}
  • Encapsulate it within functions to prevent breaking other code.
  • Throws more exceptions
  • Prevents or throws exceptions for potentially unsafe actions
  • Disables some older JavaScript features

3: Organize and Declare Variables

function () {
    "use strict";

    var i = 0,
        x = 0,
        string = "string";
        
        //Do stuff.
}
  • Strict mode will force you to declare variables using the var keyword anyway.
  • Easier for other developers to read

4: Use '===' instead of '=='

function () {
    "use strict";

    var i = 0,
        x = 0,
        string = "string",
        $headings = $('h2');
        
        if (i === x) {
            //Do stuff.
        }
}
  • Automatically evaluates variable type along with value
  • Faster
  • Keeps you honest w/ variable types

5: Assign JQuery Objects to Variables

// $('h2') has to be reevaluated each time (slower)
$('h2').addClass('secondary');

$('h2').each(function () {
    // Do stuff.
)};
// $('h2') is only evaluated once (faster)
$headings = $('h2');

$headings.addClass('secondary');

$headings.each(function () {
    // Do stuff.
});
  • Do this whenever you need to use a JQuery object more than once
  • JQuery only has to traverse DOM once.
  • Prepend JQuery variables w/ "$" to differentiate them.

6: Only Evaluate this Once

$('h2').each(function () {
    "use strict";
    if ($(this).attr('id') === 'wars') {
        console.log('star');
    } else if ($(this).attr('id') === 'fly') {
        console.log('fire');
    }
});
$headings.each(function () {
    "use strict";
    var $heading = $(this);
    if ($heading.attr('id') === 'wars') {
        console.log('star');
    } else if ($heading.attr('id') === 'fly') {
        console.log('fire');
    }
});