This pattern is quite common; I've seen it in a few places including the jQuery source code:
var arr = "word1 word2 word3".split(" ");
as an alternative to the 'normal' methods of array initiliasation:
var arr1 = [ "word1", "word2", "word3" ];
var arr2 = new Array( "word1", "word2", "word3" );
What are the benefits of the string-splitting approach?
From John Resig (creator of jQuery):
"the only benefit i see is character count in the source and one string rather than numerous." Bingo!
Now that I think about, I think Closure may optimize this point (don't think YUIMin did). I can check in to it again.
Also, the Google JavaScript Style Guide recommends avoiding new Array()
because "Array constructors are error-prone due to their arguments." The guide has a more thorough explanation.
The first is shorter. In JS libs these days that's an issue. It's also easier to write: less ,
and '
. It's also harder to mistype.
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