Wes Crow
Wes Crow

Reputation: 2967

What is the value after the comma in a JavaScript array literal definition?

I have been watching a video of a conference (See: Good JavaScript Habits for C# Developers at 13:23 in the video). The presenter has been discussing best practices in JavaScript. One of the tips he gives is to use object literal declarations which is something I am familiar with.

However, in the code he is using he declares an array using object literal notation like so:

var myArray = [], name;

I have never seen this before. I am used to the var myArray = [] part of the declaration but what is the second name value after the comma? The presenter never discusses it and I can't find any other examples of this practice. Could someone please explain what this does?

Upvotes: 1

Views: 153

Answers (2)

Adam Zalcman
Adam Zalcman

Reputation: 27233

This is simply declaration of two variables: myArray initialized to an empty array and name which isn't initialized.

Note that var may be followed by a list of variable declarations each with an optional initializer. See section 12.2 of ECMA standard 262 which defines the syntax as

VariableStatement : var VariableDeclarationList ;

Upvotes: 1

Seth
Seth

Reputation: 6260

This is chaining variables. It's the same as doing this.

var myArray = [];
var name;

You are simply saving space by defining your variables in one line.

They don't have to be on one line either.

var myArray = [],
    name;

Upvotes: 8

Related Questions