What are the benefits of splitting a string on initializing a javascript array?

This pattern is fairly common; I saw this in several places, including jQuery source code:

var arr = "word1 word2 word3".split(" "); 

as an alternative to the "normal" array initialization methods:

 var arr1 = [ "word1", "word2", "word3" ]; var arr2 = new Array( "word1", "word2", "word3" ); 

What are the benefits of a line split approach?

+6
source share
2 answers

From John Resig (creator of jQuery):

"the only advantage I see is the symbol counting in the source and one line rather than multiple." Bingo!

Now that I think I think Closing can optimize this moment (I don't think YYIMin did). I can register for it again.

In addition, the JavaScript JavaScript Style Guide recommends avoiding new Array() because "Array constructors are error prone due to their arguments." The manual contains a more detailed explanation.

+3
source

The first one is shorter. There is a problem in JS libs these days. It's also simpler: less , and. ' It is also harder to make mistakes.

+3
source

Source: https://habr.com/ru/post/887615/


All Articles