views:

128

answers:

4

I see code like this all over the web

var days= "Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split(" ");

Why do that instead of

var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];

I don't think laziness or ignorance has anything to do with it. This is out of jQuery 1.4.2

props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" ")

They do it all over the place.

+11  A: 

I think it's because you don't have to quote and separate every string of the array. Likewise, in perl, many people use qw(a b c d e f g) instead of ('a', 'b', 'c', 'd', 'e', 'f', 'g'). So the benefit is twofold:

  1. It's faster and easier to write and modify (can obviously be debatted).
  2. It's smaller bitewise, so you spare some bandwidth.

See the bite size:

var days= "Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split(" ");
// 81 characters

vs

var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
// 91 characters
Alsciende
+1, you beat me to it :-)
Andy E
Actually, it would only be 3 bytes smaller (since you would use a minifier meaning no unnecessary whitespace), but sure, it's still some bandwidth saved I guess...
Blixt
I like it. In my tests, the string split way takes about 1 and a half times as long to execute but it's really only measurable over thousands of iterations. IMO it's not easier to read but it does make the file smaller and it is faster to write.
Matthew
I agree that it's not easier to read, in part because unlike perl you don't know the string will be split until the end of the line.
Alsciende
A: 

It may also make sense if initial strings have quotes or double quotes in text.

Thevs
A: 

"81 characters and 91 characters" << Nice observation but it again adds few processing time to convert String to Array and what if sometimes there's need to add something which has 2 words in it.

May be they like this coding style.

IDK

Ashit Vora
A: 

You could have 20 strings of the week day names in 20 languages, and use a single split to return the correct array for the user.

kennebec