7

What purpose does name have in the following statement?

var myArray =[], name;

I usually initialize my arrays as the following:

var myArray =[];
burnt1ce
  • 14,387
  • 33
  • 102
  • 162

8 Answers8

18

It is shorthand to

var myArray =[];
var name;

It is matter of personal preference.

Community
  • 1
  • 1
amit_g
  • 30,880
  • 8
  • 61
  • 118
11

You are actually initialising two variables there, myArray and name.

You set myArray to [] and name to undefined, because you don't give any value.

Your code is equivalent to this:

var myArray = [];
var name;
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
8

It is equal to this:

var myArray =[];
var name;
aorcsik
  • 15,271
  • 5
  • 39
  • 49
8

In JavaScript multiple variable assignments can be separated by commas, eliminating the need for repetitive var statements.

var myArray = [];
var name;

is equivalent to

var myArray = [], name;
g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
7

This is equivalent to

var myArray =[];
var name;
trutheality
  • 23,114
  • 6
  • 54
  • 68
7

It doesn't affect myArray, it's just the same thing as

var myArray = [];
var name;
brymck
  • 7,555
  • 28
  • 31
4

It's essentially the instantiation of a second variable name with no value.

ShaneBlake
  • 11,056
  • 2
  • 26
  • 43
1

The recommended way (clean and short as possible) of writing this kind of code is the following:

var myArray = [],
    name;
antonjs
  • 14,060
  • 14
  • 65
  • 91