Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I see javascript arrays getting created with string.split()?

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.

like image 644
Matthew Avatar asked Jun 18 '10 12:06

Matthew


1 Answers

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 bitwise, so you spare some bandwidth.

See the bit 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
like image 111
Alsciende Avatar answered Dec 11 '22 05:12

Alsciende