7 Ways To Prevent JavaScript Bugs

By: Ryan Kienstra on: January 27, 2015  in: JavaScript   2 Comments

Prevent JavaScript Bugs icon
JavaScript is flexible, and it doesn’t throw many errors.

But it makes it easy to create bugs.

These 7 conventions will help you prevent JavaScript bugs.

1. Equality Operators

Use === and !==


== and !=

The expression ( foo === "" ) is more reliable than ( foo == "" ).

The operator === produces true when both operands:

  • Have the same type: ( 0 === 0 )
  • Have the same value: ( "bar" === "bar" )

But == is inconsistent.

It considers some different types to be equal.

( "" == 0 ) is true

The book JavaScript: The Good Parts states that the rules for == are too complex.

It’s better to use strict evaluation: ( foo === "" )

This will be true only if foo is an empty string.

You can also simulate ==.

( foo === "" ) || ( foo === false )

2. Variable Declaration

Declare variables at the top of the function.

Or the top of the file, if they’re not in a function.

var foo , bar , fooBar;

You might read my guide, JavaScript Variable Declaration

If you don’t use var to declare new variables, they’ll be global.

3. Function Assignment

Assign functions to variables.

var foo = function() { };

Instead of

function foo() { }

Named functions like function foo() { } are hoisted to the top of the scope.

This means they can be called before they’re declared.

function foo() {
        // omitted

This makes the scope of the function unclear.

Functions are first-class objects in JavaScript.

So programmers expect to see them attached to variables.

4. Semicolons

Use a semicolon at the end of every single-line expression.

var firstVal = 23;

Unlike PHP, JavaScript won’t throw an error for a missing semicolon.

But it may produce the wrong result.

Lines that don’t end with a semicolon may get one added automatically.

The book JavaScript: The Good Parts states that this will return nothing:

{ foo : foo
  bar : bar

The JavaScript engine will add a semicolon after return.

return; // added semicolon
{ foo : foo
  bar : bar

It will return before it gets to { foo : foo.

Using semicolons will prevent JavaScript bugs and make your code clearer.

5. Addition

+ is the addition and concatenation operator.

If one of the operands is a string, and one is a number, it produces a string.

'foo' + 21 results in the string 'foo21'.

So one accidental string can cause a serious bug.

When adding numbers, you might verify they’re actually numbers.

function fooAddition( val ) {
        if ( isNaN( val ) ) {
                throw new Error( 'Argument of fooAddition is not a number' );
        // omitted

6. Object Variables

Browsers won’t throw an error if you try to access a non-existent variable in an object.

You’ll only get undefined

var exampleObject = {
        foo : 'foo_value' ,
        bar : 'bar_value' 
var nonExistentValue = exampleObject.wrongKey;

nonExistentValue will be undefined

You can check to see if it has the variable:

if ( exampleObject.hasOwnProperty( 'wrongKey' ) )

7. Modules

Simple objects don’t have private variables.

For example, exampleObject.foo = 'new_value' overwrites the previous value.

Modules can have private variables, though.

Modules prevent JavaScript bugs by hiding implementations.

The free book JavaScript Design Patterns describes modules in detail.

My guide, JavaScript Modules in WordPress shows how to use them.

And how they work.

var myModule = ( function() {
        var myVar = 'fooBar'; // private 

        return {
                getVar : function() {
                                return myVar;
                         } ,
                setVar : function( val ) {
                                myVar = val;

} )();

myVar is private because myModule doesn’t return it.

myModule.myVar produces undefined

Only the functions that are returned are public: getVar and setVar

myModule.getVar() will return 'fooBar'

Prevent JavaScript Bugs

It’s easy to create bugs in JavaScript.

The language doesn’t throw many errors.

It may even “correct” improper code, like when it adds semicolons.

But these 7 conventions will help you prevent JavaScript bugs.

So you can use the flexibility of JavaScript to your advantage.

  2 comments   Comment

    • 7 years ago  

      Ryan Kienstra

      Thanks, Weston. That’s a great point. I’ll set up the .jshintrc to detect these issues.

Leave a comment