Jeremy was sent hunting a bug in some older JavaScript code. The key problem was that many phone numbers were getting a US country code prepended to them, even when they already had a different country code and were in a different country than the US.

for(i in item.victims) {
        c = item.victims[i].country_code;
        n = item.victims[i].phone_number;
        if(n) {
                number = c ? c + '' + n : n
                if(number in Account.contacts) {
                        number = Account.contacts[number];
                } else {
                        if(n.length == 10 || (n[0] == 1 && n.length > 10)) {
                                s = n[0] == 1?1:0;
                                number = '1 (' + n.substring(s, s+3) + ') ' + n.substring(s+3, s+6) + '-' + n.substring(s+6, s+10);
                        } else {
                                number = '+' + c + ' ' + n;

So this code examines each victim. We start by combining their phone number with their country code, and if we haven't already tracked this one in contacts, we inspect it. And this is where it gets weird.

First, we have our ternary, s = n[0] == 1?1:0;: if n[0] is 1, s will equal 1, otherwise 0. Then we use s to do some string mangling through the phone number to shove dashes and other characters in.

It's ugly code, confusing to read code, but most important: it's wrong code. It assumes that phone numbers that have 10 digits are North American, and thus start with a 1 in the country code. Unfortunately: this isn't true, and this application isn't meant to service only North America.

In the end, it's time to brush up on Falsehoods Programmers Believe about Phone Numbers.

[Advertisement] Continuously monitor your servers for configuration changes, and report when there's configuration drift. Get started with Otter today!