The Single Worst Thing about JavaScript

There are many weird things about JavaScript, the DOM, and related web tech. Many quirks, oddities, frustrations, and wtfs.

But there is one “worst thing” and the worst thing in JavaScript is String.prototype.split() (es5 15.5.4.14)

String.prototype.split() is defined to take a separator and a limit as its arguments, operating on the “this” object internally for the string object to operate on. The way “limit” works is what makes this the worst thing about JavaScript.

In ruby, The separation at the split is done at most limit-1 times, with max limit number of elements returned.

> "a-b-c-d-e-f".split("-",3)
=> ["a", "b", "c-d-e-f"]

Java has the same behavior

String[] parts = "a-b-c-d-e-f".split("-", 3);
=> ["a", "b", "c-d-e-f"]

Perl has that same behavior as well

split('-','a-b-c-d-e-f',3)
=> ["a", "b", "c-d-e-f"]

In python, the limit is the number of times the string is split on the separator, with the final element of the array being the rest of the string (split max limit times, max limit+1 elements returned). It’s not the same, but you’re still getting all the parts necessary to do what you need.

>>> "a-b-c-d-e-f".split('-',2)
=> ['a', 'b', 'c-d-e-f']

In JavaScript? Well, this is what you get in JavaScript:

"a-b-c-d-e-f".split('-',2)
=> ["a", "b"]

What happens to the rest? Who knows! Who cares, right? That isn’t useful at all! Don’t even pay attention to the fact that the limit is completely irrelevant and can be easily (and more intuitively) attained by “a-b-c-d-e-f”.split(‘-‘).slice(0,2).

And that is the worst part of JavaScript.

Everything else is mostly OK.

One thought on “The Single Worst Thing about JavaScript”

Leave a Reply