I've seen a few javascript programmers use this pattern to produce an array:
"test,one,two,three".split(','); // => ["test", "one", "two", "three"]
They're not splitting user input or some variable holding a string value, they're splitting a hard-coded string literal to produce an array. In all of the cases I've seen a line like the above it would seem that it's perfectly reasonable to just use an array literal without relying on split
to create an array from a string. Are there any reasons that the above pattern for creating an array makes sense, or is somehow more efficient than simply using an array literal?
When splitting a string at run-time instead of using an array literal, you are trading a small amount of execution time for a small amount of bandwidth.
In most cases I would argue that it is not worth it. If you are minifying and gzipping your code before publishing it, as you should be, using a single comma inside of a string versus a quote-comma-quote from two strings in an array would have little to no impact on bandwidth savings. In fact after minification and gzipping, the version using the split string could possibly be longer due to the addition of the less compressible .split(',')
.
Splitting a string instead of creating an array literal of strings does mean a little less typing, but we spend more time reading code than writing it. Using the array literal would be more maintainable in the future. If you wanted to add a comma to an item in the array, you just add it as another string in the array literal; using split
you would have to re-write the whole string using a different separator.
The only situation that I use split
and a string literal to create an array is if I need an array that consists only of single characters, i.e. the alphabet, numbers or alphanumeric characters, etc.
var letters = 'abcdefghijklmnopqrstuvwxyz'.split(''),
numbers = '0123456789'.split(''),
alphanumeric = letters.concat(numbers);
You'll notice that I used concat
to create alphanumeric
. If I had instead copy-pasted the contents of letters
and numbers
into one long string this code would compress better. The reason I did not is that that would be a micro-optimization that would hurt future maintainability. If in the future characters with accents, tildes or umlauts need to be added to the list of letters, they can be added in one place; no need to remember to copy-paste them into alphanumeric
too.
Splitting a string may be useful for code golf, but in a production environment where minification and gzipping are factors and writing easily readable, maintainable code is important, just using an array literal is almost always the better choice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With