Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the advantages of splitting a string to initiliase a javascript array? [closed]

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?

like image 990
Bobby Jack Avatar asked May 09 '11 12:05

Bobby Jack


2 Answers

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.

like image 122
McStretch Avatar answered Oct 24 '22 03:10

McStretch


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.

like image 32
Rudie Avatar answered Oct 24 '22 02:10

Rudie