Using comma in Javascript variable declaration
I just came across the following code:
function showMatch(str, reg) {
var res = [], matches
while(true) {
matches = reg.exec(str)
if (matches === null) break
res.push(matches[0])
if (!reg.global) break
alert(res)
}
Can anybody please explain the second row? Does
var res = [], matches
equal
var res=[]; res=matches
or
var res=[]; var matches=[]
?
I guess the second answer is correct? I find this little confusing...
Solution 1:
It equivalent to
var res = [];
var matches;
where matches
is undefined
Solution 2:
It's equivalent to:
var res=[];
var matches;
When you declare variables, you can put them in the same var
statement, separated by commas:
var a, b, c, d, e;
Any of the variables may be initialised with a value:
var a, b = 42, c, d = {}, e = "Hello world";
Declaring all the variables in a function at the top of the code is usually done to better represent what's actually happening in the code (and to get a better overview of the variables used). Any variable declarations in a function are hoisted to the top of the code, so they all exist before the code stars executing. That mean that you can use a variable before the declaration statement. Example:
a = 42;
var a;
alert(a); // shows 42
If you use several variables in a function, you may find it useful to declare them at the beginning of the function. The important part is to declare the variables that you want to create in the function. If you forget to declare a variable and use it anyway, it will implicitly be declared as a global variable, which may interfere with code elsewhere.