7

What purpose does name have in the following statement?

var myArray =[], name;

I usually initialize my arrays as the following:

var myArray =[];
burnt1ce
  • 13,737
  • 31
  • 99
  • 151

8 Answers8

18

It is shorthand to

var myArray =[];
var name;

It is matter of personal preference.

Community
  • 1
  • 1
amit_g
  • 29,985
  • 8
  • 58
  • 117
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
  • 224,675
  • 49
  • 309
  • 312
8

It is equal to this:

var myArray =[];
var name;
aorcsik
  • 14,571
  • 4
  • 38
  • 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
  • 44,141
  • 8
  • 97
  • 109
7

This is equivalent to

var myArray =[];
var name;
trutheality
  • 22,216
  • 6
  • 48
  • 65
7

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

var myArray = [];
var name;
brymck
  • 7,424
  • 26
  • 30
4

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

ShaneBlake
  • 10,946
  • 2
  • 25
  • 43
1

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

var myArray = [],
    name;
antonjs
  • 13,574
  • 11
  • 62
  • 91