How to reduce bugs in JavaScript code by following the rule of consistent types

Tags:

One of the most annoying type of bug in JavaScript code is when the code doesn’t have logical types. Oh hey, I’ll just sum these two numbers… NOPE! They’re actually strings! That just makes me so angry. To make matters worse, this is something I’ve had to deal with a lot with a codebase I’ve been working with recently.

JavaScript is dynamically typed, and it doesn’t care what you do with its variables. You can have a variable contain a boolean, then put an array into it… then put a number into it… but this does not mean you should.

Your values should have one type only

Sometimes you see code like this

function getNames(person) {
  if(person.firstName == '') {
    return false;
  }
 
  return [person.firstName, person.lastName];
}

At a glance, it doesn’t look like there’s anything wrong with it. However, it breaks a very important rule you should follow to keep typing-related bugs away from your code.

In a language with static typing, the above would not work. The problem is that the function has inconsistent return types. What this means is the function can return both a bool value, and an array value. That kind of thing would never fly in a statically typed language, and there’s a very good reason why you should never do this in a dynamically typed language either.

Inconsistent types will give you a headache

When a function returns different types, you can’t make any kind of assumptions about its output. As a result, it will cause a mess, both in code and possibly in bugs as well.

Let’s say you take the above function and want to combine the names…

var result = getNames(person);
var combined = result.join(' ');

Now what will happen when the function takes the first path and returns a bool? A “true” or “false” value does not have a function join in them, therefore it will cause the code to throw an error. In order to deal with the possibility of a bool instead of an array, we have to add all this useless fluff into the code

var result = getNames(person);
var combined = '';
if(typeof result != 'boolean') {
  combined = result.join(' ');
}

Now, the example above is very simple. If you have ever worked on a large JavaScript codebase that broke this rule, you already know how bad it will get in a real application.

Always be mindful of your types

In order to fix this problem, we can simply rewrite the function like so

function getNames(person) {
  if(person.firstName == '') {
    return [];
  }
 
  return [person.firstName, person.lastName];
}

By keeping the return type consistent, we reduce the likelihood of bugs being caused by incorrect types. We also reduce the amount of code that you need to write, and less code is always better than more code.

Working in dynamic languages like JavaScript gives you great freedom, but with great freedom comes great responsibility. Save yourself the headaches, and keep your types consistent!