- Published on
Loosely Typed Code Deserves Triple Equality
- Authors

- Name
- Kevin van Zonneveld
- @kvz
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 unintended 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.
Legacy Comments (3)
These comments were imported from the previous blog system (Disqus).
"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."
Welcome to loosely typed language - it's not a bug, it's a feature
Yeah, I'm doing some Go programming too and typed and loosely typed languages both have their (dis)advantages. Anyway this is an attempt to help mitigate the disadvantages of loosely typed languages a little. I changed the wording of this post to reflect that more. Thanks for your input!