Loosely Typed Code Deserves Triple Equality

1 minute read

In loosely typed languages such as JavaScript or PHP, using == to compare values is bad practice because it doesn't account for type, hence false == 0 == '' == null == undefined, etc. And you may accidentally match more than you bargained for.

If you want you can limit unintented effects & bugs this may lead to, it's often wise to use ===.

In the process of converting legacy codebases to use these triple equality operators, I find that as a rule of thumb you can almost always force triple equality in case of comparing variables against non-numerical strings.

There's just never a case where you want the text 'Kevin' to pass for the boolean true, or the number 3. And if that can still happen in your legacy codebase, you'll want to limit those risks rather sooner than later. Even if that breaks things that now accidentally, work.

Switching legacy code that compares against numerical strings, numbers, or booleans is trickier. For instance user input often arrives as a string, so bluntly changing age == 4 to age === 4, will now no longer match the user input age, and introduce more problems than it solves. Addressing these cases needs more thought & care.

To change all of the text-compare cases, here's a regex that can, to a degree, automate this otherwise much more painful process.

([0-9a-zA-Z\_]\s+[!=])=(\s+['"][^0-9\-\.])
$1==$2

You could use this in a programs like Vim or Araxis, or escape it and then use it in sed. Make sure the changes are under source control and reviewed & tested before committed & pushed.

I tested this on legacy JavaScript and PHP projects. Here you can see the potential issues caught in php.js

Improvements welcome.

Leave a Comment Right Here