Javascript recommendations, why use a comma to declare a chain of functions / variables?

I am developing a jQuery plugin "jQueryLog" to enable debugging of a chain of selectors and return values. If you want to check it out, you can do it here.

This is the second version. The first version was actually edited jQuery, and doing this I had to read jQuery to understand how the internal elements work. The question comes from there:

var jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // A central reference to the root jQuery(document) rootjQuery, // A simple way to check for HTML strings or ID strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, (...) 

Is there a big reason to use the declaration chain + comma instead of using:

 function jQuery ( selector, context ) { ... } var _jQuery = window.jQuery; var _$ = window.$; etc... 

The only reason I see here is because the minifier has fewer literals that cannot be cut down. But are there any other reasons?

+6
source share
1 answer

This is simply a shorter way to keep all variables in the function area, making sure they are not used until they are defined.

In JavaScript Templates (September 2010, O'Reilly) Stoyan Stefanov calls this a single var template :

JavaScript allows you to have multiple var statements anywhere in a function, and they all act as if the variables were declared at the top of the function. This behavior is known as raising .... You use a single var statement and declare multiple variables separated by commas. It is also recommended that you initialize the variable using the initial value at the time it is declared. This can prevent logical errors (all uninitialized and declared variables are initialized to undefined ), as well as improve code readability.

+5
source

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


All Articles