amnesia amnesia - 7 months ago 42
Javascript Question

In Javascript, why define an array with split?

I frequently see code where people define a populated array using the split method, like this:

var colors = "red,green,blue".split(',');

How does this differ from:

var colors = ["red","green","blue"];

Is it simply to avoid having to quote each value?


Splitting a string is a bad way of creating an array. There several issues with the approach that include performance, stability and memory consumption. It requires CPU time to parse the string, it is prone to errors (double commas, spaces in the string, etc.) and means your script essentially has to store twice as much data in memory.

It's not a good idea and is most likely just a bad habit someone picked up when they first learned about strings and arrays. That or they're trying to be clever for some kind of coding exercise.

As a rule of thumb, the only time you should be parsing strings into arrays is if you're reading that string data from an external source and need to convert it to native types. If you already know the values ahead of time, you should create the array yourself.

The one possible reason someone might do this is to reduce the number of characters in their source code, trading performance for bandwidth. 'abcdef'.split() is fewer characters than ['a','b','c','d','e','f'].